Reputation: 2074
I have a file test, with the content
Hi
Hello
I am good.
My requirement is I have to write a shell script to search Hello
sting in the file test and add a new line after it with the content got it
.
For this I am using command:
sed '/Hello/ a "got it"' test
I am getting the below error for this command:
sed: command garbled: /Hello/ a "got it"
Upvotes: 1
Views: 11026
Reputation: 1215
sed command to search string and append a line after searched string
You can use regex capture groups.
In sed you have to escape the parenthesis.
To reuse the captured content you can use \1
(1 for the number of the capture - afaik up to 9 in sed )
generally it looks like:
echo "barfoobaz" > /tmp/file
sed -i 's/bar\(foo\)baz/ new \1 text/g' /tmp/file
cat /tmp/file
# new foo text
How to add a new line now?
During the replace step you add the newline character \n
into the replacement string:
echo "Hi" > /tmp/file
echo "Hello" >> /tmp/file
echo "I am good." >> /tmp/file
sed -i 's/\(Hello\)/\1\ngot it/g' /tmp/file
Upvotes: 0
Reputation: 195179
try:
sed '/Hello/a got it' file
a
is append command. read man sed
for detail
test with your example:
kent$ echo "Hi
Hello
I am good."|sed '/Hello/a got it'
Hi
Hello
got it
I am good.
Upvotes: 2
Reputation: 955
@Kishore, your "command garbled" error probably indicates that you used an "AltGr + Space" instead of a space when typing your command, or that you failed to use regular upright single quotes.
In fact the spaces are not necessary at all, and if you just want to put "got it" on the line following the match, just go:
sed '/Hello/agot it' test
It works perfectly well, the backslash in @Kent's solution is not necessary.
Upvotes: 0