user1987607 user1987607 - 3 months ago 18
Linux Question

linux add string to beginning of specific lines

I have a tab-delimited text file,starting with some lines that start with '#'.

#line1
#line2
#line3
1 a
1 b


Now for every line that doesn't start with '#', I want to add a string 'text'.

#line1
#line2
#line3
text1 a
text2 b


How can I do this? I thought of working with sed

sed "s/^[^#]/text/g" infile > outfile


But then the output for the first column on every line is just 'text' and not 'text1' or 'text2'.

Answer

You need to capture and then reference the character matched by [^#]:

sed 's/^[^#]/text&/' infile > outfile