I'm trying to substitute (with sed
) an entire line containing a specific word and the newline at the end. Here the testfile:
this # target for substitution
this is a test
another test?
Now, I already posted here, and from the linked post, I understand how to do this in some way:
sed 's/^this$/test/g' testfile
That works, or at least it seems so, because the newline at the end of the word this
is still there:
test # target for substitution but newline is still there
this is a test
another test?
Given the above, I'm also fully aware sed
can't match the newline directly (although I do recall that I could use '\n' in certain version of sed
, but that's beside the point).
I do know how to at least delete the entire word/line and the newline:
sed '/^this$/d' testfile
Except I need to substitute it instead.
How can I do this? (with sed
preferably)
this
andthis is a test
by a single linetestthis is a test
. Is that correct? It's not easy to join two lines together in sed; see examples in the manual. You could use awk, which can read the next line:awk -v replacement=test '/^this$/ { getline; print replacement $0 }' testfile
awk '{if (/^this$/) {sub(/^this$/, "test"); printf "%s", $0;} else print }' file
sed
? There is theN
command for this. Nothing more simple.sed
versions, you can match a newline in the search pattern with\n
. What you recall applies to the replacement pattern.