1

I have one file named "test-file". It has just two following lines (one line with # sign in the front and second line with same content but without hash):

#contents of line
contents of line

I want to update/replace the contents of second line by using sed command. I know its simple syntax for example:

sed -i 's/.*contents of line.*/updated contents/' test-file

but the above command is replacing both of the lines whereas I don't want to update the first line with # sign in the front.

3

try

sed 's/^[^#]*contents of line.*/updated contents/' test-file

or with the start of line anchor ^, and you know that line start with content ..., you could do:

sed 's/^contents of line.*/updated contents/' test-file

If you know which line you are going to update, you can change directly with its address line number like.

sed '2s/.*/updated content/' test-file

add -i when you were happy with the result.

5

You could do the edit the following way:

sed -e '/^#/!s/.*/UPDATED_CONTENTS/' input-file.txt

or

sed -e '/^#/!c\
UPDATED_CONTENTS' input-file.txt

this is to read as: for any line that does not begin with a # , change that whole line to what is specified.

And in case you are concerned that the octothorpe can be preceded by blanks, then tweak the regex to /^[[:blank:]]*#/ while keeping the rest exactly as is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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