0

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?

paul23
  • 8,799
  • 12
  • 66
  • 149

3 Answers3

2

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

sneep
  • 1,828
  • 14
  • 19
  • this assumes GNU sed, for both `-i` option as well as `i` command... see https://stackoverflow.com/questions/5694228/sed-in-place-flag-that-works-both-on-mac-bsd-and-linux and https://www.gnu.org/software/sed/manual/sed.html#Other-Commands – Sundeep Mar 24 '18 at 06:12
  • Ah. Didn't know that. : – sneep Mar 24 '18 at 06:16
0

Solution with awk:

#!/bin/sh
TMP="a b c"
exec 3<> tmp.txt && awk -v TEXT="$TMP" 'BEGIN {print TEXT}{print}' tmp.txt >&3

solution from John Mee

Marko
  • 83
  • 1
  • 7
0

Using ed with commands read from a here-doc

ed tmp.txt <<END_ED_COMMANDS
1i
$TMP
.
w
q
END_ED_COMMANDS
glenn jackman
  • 238,783
  • 38
  • 220
  • 352