Sed Add Line (Without Spaces at the Beginning ) After Match (Script Using Variables )
Please Help with Spaces When Script Add Line After Searched Pattern $ Cat Test. Txt Test Server:1 Prod Server 1 $ Cat. /Check. Sh #! /Bin/Bash # Search=" Test...
Please help with spaces when script add line after searched pattern
$ cat test.txt
test server:1
prod server 1
$ cat ./check.sh
#!/bin/bash
#
search=" test server:1"
add=" test server:1000"
echo "starting"
sed -e "/${search}/a${add}" ./test.txt
$ ./check.sh
starting
test server:1
test server:1000
prod server 1
spaces before: test server:1000 are lost. How can I fix this?
2 Answers
What you're seeing is a subtle difference between the GNU extended command
a textAppending text after a line. This is a GNU extension to the standard a command - see below for details.
in which the manual notes that
Leading whitespace after the a command is ignored.
and the original and more portable form
a\ text
which does not strip leading whitespace. There are several ways to get the latter behavior in a "one-liner" e.g.
$ sed "/${search}/a\\${add}" ./test.txt
test server:1
test server:1000
prod server 1
(note the \ needs to be escaped within double quotes) or
$ sed "/${search}/a"'\'"${add}" ./test.txt
test server:1
test server:1000
prod server 1
or
$ sed -e "/${search}/a\\" -e "${add}" ./test.txt
test server:1
test server:1000
prod server 1
(although note that the last one relies on another GNU extension, -e).
You need to escape the space, otherwise sed will ignore it because /pattern/atext and /pattern/a text and /pattern/a text is interpreted the same.
Use this:
sed -e "/${search}/a${add// /\\ }" ./test.txt