Reputation: 9455
How would I use a variable -containing spaces- as values in sed? - I'm using sh
(not bash
) as terminal.
What I'm trying to do (insert a b c
in the first line of the file):
TMP='a b c'
sed -e '1i'${TMP} tmp.txt
However this errors with the message
dynamic-config-manager-nginx.sh: -: not found
And in the files I only see the first a
inserted. - It seems that sed
is exiting too early. "forcing" quotes around the string like below also doesn't work, with "
command not found
sed -e '"1e'${TMP}'"' tmp.txt
So how do I make this work?
Upvotes: 0
Views: 945
Reputation: 247210
Using ed
with commands read from a here-doc
ed tmp.txt <<END_ED_COMMANDS
1i
$TMP
.
w
q
END_ED_COMMANDS
Upvotes: 0
Reputation: 93
Solution with awk:
#!/bin/sh
TMP="a b c"
exec 3<> tmp.txt && awk -v TEXT="$TMP" 'BEGIN {print TEXT}{print}' tmp.txt >&3
Upvotes: 0
Reputation: 1918
I think you want the -i
option, to edit inplace. This gets us here:
$ sed -i -e '1i'${TMP} tmp.txt
sed: can't read b: No such file or directory
sed: can't read c: No such file or directory
${TMP}
will be expanded to multiple arguments to sed
. We want it all in a single string though:
sed -i -e "1i${TMP}" tmp.txt
One more caveat: tmp.txt
must contain at least one line. If you know that tmp.txt
doesn't exist or is an empty file, maybe do something like echo > tmp.txt
first (warning: this will overwrite the file if it contained something).
Upvotes: 2