Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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. :)

share|improve this question

3 Answers 3

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.

share|improve this answer

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
share|improve this answer

This might work for you (GNU sed):

sed -i '/^\s*$/,/\S/{/\S/s/^/#/}' file1 file2 file....
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.