user1987607 user1987607 - 2 months ago 4
Linux Question

linux add string to beginning of specific lines

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

1 a
1 b

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

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'.


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

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