I would like to take the first 2 lines from test.txt:
hello
my
name
is
and put them at the top of a new file, output.txt:
foo
bar
with the desired output being, output.txt:
hello
my
foo
bar
using sed. However, using:
text=$(head test.txt -n 2) | sed -i "1i $text" output.txt
returns the error:
sed: -e expression #1, char 10: extra characters after command
What am I doing wrong?
First you don't have to use pipe between the variable assignment text=
and the sed
command. You need to replace with the command delimiter ;
.
Second, you can get the error because part of the replacement text is interpreted by sed
. You actually need to quote the replacement string. This can be done with the bash
parameter expansion operator @Q
.
text=$(head -n2 test.txt)
sed -i "1i ${text@Q}" output.txt
As mentioned in the bash
man pages:
${parameter@operator}
...
Q The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
Obviously inserting before line 1 is the same as doing:
head -n2 text.txt > /tmp/temp.txt
cat output.txt >> /tmp/temp.txt && mv /tmp/temp.txt ouput.txt
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments