1

I have been trying quite a few ways with no luck. I have a file named test.txt that has some lorem ipsum and the text [staging: production] I simply want to add a few lines that I have saved in a variable in before it.

If you could explain where I have gone wrong with any of the below it would be much appreciated!

#!/bin/bash

test="lala\
kjdsh"

sed '/^#$/{N; /[staging: production]/ i \
<Location /cgis> \
</Location>\

}' ./test.txt


sed -i -e 's/\[staging\: production\]/\$test/g' ./test.txt
#sed -i 's/Lorem/beautiful/g' test.txt

#awk -v data=$test '{A[NR]=$0}/\[staging\: production\]/{ print data }' test.txt > testfile.txt

#read -a text <<<$(cat test.txt)
#echo ${#text[@]}
#for i in ${text[@]};
#do
#   echo -n $i;
#   sleep .2;
#done

#ed -s test.txt <<< $'/\[staging\: production\]/s/lalalala/g\nw'

#awk -v data=$test '/\(/\[staging\: production\]\)/ { print data }' test.txt > testfile.txt

# && mv testfile.txt test.txt

#sed -i -e '/\(\[staging\: production\]\)/r/$test\1/g' test.txt

#sed "/\(\[staging\: production\]\)/s//$test\1/g" test.txt
1
  • When you use a backslash as a line continuation character, the lines are joined as if there's no newline. Remove the backslash and the newlines will be preserved. Commented Aug 13, 2012 at 23:37

3 Answers 3

1
sed -i -e 's/\[staging\: production\]/\$test/g' ./test.txt

won't work because inside singe quotes BASH will not expand \$test.
Therefore you don't need to escape the $.

If you want to substitute with the contents of the variable $test do:

sed -i -e 's/\[staging: production\]/'$test'/g' ./test.txt

You also do not need to escape :

To insert before your pattern works for me this way:

sed -i -e '/\[staging: production\]/ i '$test'' ./test.txt

However to preserve the linebreak inside the variable I needed to define:

test="lala\nkjdsh"

Please note the \n to encode the linebreak.

Sign up to request clarification or add additional context in comments.

3 Comments

That appears to be working, however, it is not preserving the new lines in my variable.
I keep getting sed: 1: "/[staging: production\ ...": command i expects \ followed by text
well as I said - I had to encode the linebreaks inside the variable via \n - that did preserve the linebreaks in my environment.
0

Try it in perl, it seems to work fine:

perl -pe '{$rep="what\nnow"; s/(\[foo foo2\])/$rep$1/}' file

Comments

0

This might work for you (GNU sed):

test="lala\\                                   
kjdsh"
sed '/\[staging: production\]/i\'"$test" test.txt

N.B. \\ in the variable and the variable is surrouded by "'s in the sed command.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.