Sed --- replace a character in a matched line in place?
Use the string you are looking for as the selector for the lines to be operated upon:
sed '/ipsum/s/#//g'
/ipsum/
selects lines containing "ipsum" and only on these lines the command(s) that follow are executed. You can use braces to run more commands
/ipsum/{s/#//g;s/@/-at-/g;}
$ cat input.txt
# lorem ipsum blah variable
# lorem ipsum blat variable
# lorem ipsum blow variable
# lorem ipsum blip variable
# lorem ipsum blue variable
then:
$ sed 's|# \(.*blue.*\)|\1|' input.txt
gives:
# lorem ipsum blah variable
# lorem ipsum blat variable
# lorem ipsum blow variable
# lorem ipsum blip variable
lorem ipsum blue variable
It works as follows:
The s
tells sed
that it should substitute what the regular expression finds.
The pattern is # \(.*blue.*\)
which breaks down to: Find a hash followed by a space. The bracket (\(
) starts the grouping. .*blue.*
is the word blue
with anything before and after. The next bracket (\)
) closes the grouping.
The replacement is \1
which is a back-reference to the content of the first grouping bracket.
You can use the POSIX tool ex
:
ex a.txt <<eof
/Sunday/ sub/Sun//
xit
eof
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html