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    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?

4

2 Answers

What you're seeing is a subtle difference between the GNU extended command

a text

Appending 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).

2

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
0

Your Answer

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

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest