0

I want to insert a text from variable at the certain line of a text file.

$cat foo
hello
hello
$var=`cat foo`
$echo "$var"
hello
$cat bar
some
text

I want to insert $var into second line, but sed does not read the content of the variable:

sed -i -e '2i$var\' bar
hello
$var
world

I guess because of two identical words in foo, I'm getting this:

sed: -e expression #1, char 11: extra characters after command
Josef Klimuk
  • 1,596
  • 1
    A better way to do that IMHO would be to use the r command, with its input from /dev/stdin e.g. sed '1r /dev/stdin' bar <<< "$var". That way, there's no danger of the contents of $var being treated as part of an expression. Of course in your example (where $var consists of the contents of file foo), you can skip the variable altogether and just do sed '1r foo' bar – steeldriver Jun 19 '18 at 11:32
  • @steeldriver Great, exactly what I was looking for! ! Thanks – Josef Klimuk Jun 19 '18 at 11:39

1 Answers1

3

You call variables in sed with double quotes

sed -i -e "2i$var" bar
cmak.fr
  • 8,696
  • I guess the slash was one of the problem – Josef Klimuk Jun 19 '18 at 10:33
  • 1
    @JosefKlimuk: There are two problems in the example of the question: sed -i -e '2i$var\' bar. The first problem are the single quotes - inside them them the character $ doesn't have special meaning. The second is the backslash, indeed - it escapes the special meaning of the second single quote mark. – pa4080 Jun 19 '18 at 10:44
  • @pa4080 Thanks. And what about my $var is two identical strings? It also gives out a problem, look in my edited question. – Josef Klimuk Jun 19 '18 at 10:52