You can “uncomment a line” in a configuration file by removing the # at the start of the line. Or, to “comment out” a line, add a # character to the start of the line. (Note that some languages have different comment formats, so this may not be true if you're working with a source code file.)
Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.
Press CTRL + V to enable visual block mode. Move down and select the lines till you want to uncomment. press x and it will uncomment all the selected lines at once.
Yes, to comment line containing specific string with sed, simply do:
sed -i '/<pattern>/s/^/#/g' file
And to uncomment it:
sed -i '/<pattern>/s/^#//g' file
In your case:
sed -i '/2001/s/^/#/g' file (to comment out)
sed -i '/2001/s/^#//g' file (to uncomment)
Option "g" at the end means global change. If you want to change only a single instance of pattern, just skip this.
Try this sed
command,
sed -i '/^#.* 2001 /s/^#//' file
To complement @Avinash Raj's helpful answer with a more generic, POSIX-compliant solution.
Note that the solution is awk
-based, because a robust portable solution with sed
is virtually impossible due to the limitations of POSIX' basic regular expressions.
awk -v commentId='#' -v word='2001' '
$0 ~ "(^|[[:punct:][:space:]])" word "($|[[:punct:][:space:]])" {
if (match($0, "^[[:space:]]*" commentId))
$0 = substr($0, RSTART + RLENGTH)
else
$0 = commentId $0
}
{ print }
' file > tmpfile.$$ && mv tmpfile.$$ file
(^|[[:punct:][:space:]])
and ($|[[:punct:][:space:]])
are the POSIX extended regex equivalents of the \<
and \>
word-boundary assertions known from other regex dialects.awk
doesn't offer in-place updating (neither does POSIX sed
, incidentally), hence the output is first captured in a temporary file and that file then replaces the original on success.Quick example of how to comment and uncomment a line in a file.
Sample file :
umask 027
TMOUT=600
Lets now backup the file (just for laughs) and comment out and un comment:
# backup file (because we should always do this)
cp /etc/bash.bashrc /etc/bash.bashrc.$(date '+%Y-%m-%d,%H:%M:%S')
# original: TMOUT=600 , result :# TMOUT=600
sed -i '/[^#]/ s/\(^TMOUT=600.*$\)/#\ \1/' /etc/bash.bashrc
# original # TMOUT=600 ,result :TMOUT=600
sed -i '/^#.*TMOUT=600.*$/s/^#\ //' /etc/bash.bashrc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With