bashreplacesedgrepcomments

Using sed to retrieve and modify a single line in the file


I have a bash script that needs to comment out the first non-comment line from a file and display it, like this:

env=$(grep -v -m 1 "#" file)
if [ "$env" != "" ]
then
    sed -i "/\<$env\>/s/^/#/" file
fi
echo $env

which turns this:

#this is an example file
this is the first line
this is the second line

Into This:

#this is an example file
#this is the first line
this is the second line

And echoes this this is the first line

I believe there is a more straight forward, canonical way of doing this, maybe by using sed only. It would be convenient for it to be a one-liner, because it is actually executed over ssh. On the other hand, execution over ssh causes problems with expanding environment variables within sed arguments, and escaping it with \\\$env does not work. Any suggestion is greatly appreciated.


Solution

  • As you already suggested, you can use sed only:

    sed '0,/^[^#]/ s/^[^#].*/#\0/' file.txt
    

    The above sed command applies to a range from the first line in the file until the first uncommented line. In this range it replaces the start of an uncommented line with a #. Because the range just applies until the first uncommented line, only this one will be commented.