0

I have a bunch of files, which I would like to use # to comment the 1st non-blank line, the files are not in good format, so there may be 1 or multiple blank lines before the line I want to comment. Any way I can do it? thanks!

As an example:

File1:

<blank Line>
this is line 1, and I want to comment.
This is line 2...

File2:

<blank line>
<blank line>
This is line 1, and I want to comment.
This is line 2...

Hope I have state the questions clearly. :)

3 Answers 3

2
echo -e '\n  \nfoo\nbar' | awk '!p && /[^[:blank:]]/ {$0 = "#" $0; p=1} 1'
<empty>
<space><space>      
#foo
bar

when "p" == 0 and a line with a non-space character appears, add a hash and set p=1. Print every line.

0

Using sed as OP required.

sed ':loop;$!{N; b loop};s/^[ \t\n]*/&#/' file

Test file

<empty>
<space><space>    
<tab><tab>  
foo
bar

result

<empty>
<space><space>    
<tab><tab>  
#foo
bar
0

This might work for you (GNU sed):

sed -i '/^\s*$/,/\S/{/\S/s/^/#/}' file1 file2 file....

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .