0

source file:

$cat test.file 
aaa
bbb
ccc

I want to insert echo test> /var/tmp/file into the second line, and the desired result is like this:

$ cat test.file 
aaa
echo test > /var/tmp/file
bbb
ccc

I tried the following, but failed :(

$ sed -i "2 s/^/echo test > /var/tmp/file\n/" test.file                                          
sed: -e expression #1, char 20: unknown option to `s'

$ sed -i "2 s/^/"echo test > /var/tmp/file"\n/" test.file 
-bash: /var/tmp/file\n/: Is a directory
2

2 Answers 2

3

Try:

sed '2i echo test > /var/tmp/file' infile

2i says insert text at second line.


your own solution also should work, but since there are / in your text that you want add and sed itself also using / character for substitution character, so they will conflict with each other.

You have two ways to fix this:

  1. change sed / substitution character to something else that do not exists in your input file:

    sed '2 s:^:echo test > /var/tmp/file\n:' infile
    
  2. escape all / characters from your text you are going to add to your file.

    sed '2 s/^/echo test > \/var\/tmp\/file\n/' infile
    

add -i switch for in-place replace to your command when you were happy with the result.

sed -i '2 s/^/echo test > \/var\/tmp\/file\n/' infile
0
0

With this there's no need to escape any characters. The r read file command will place the contents of the file after the specified line number, in this case after Iine #1.

$ echo 'echo test > /var/tmp/file' \
| sed -i '1r /dev/stdin' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .