Reputation: 123
I want to add a new line to the top of a data file with sed, and write something to that line.
I tried this as suggested in How to add a blank line before the first line in a text file with awk :
sed '1i\
\' ./filename.txt
but it printed a backslash at the beginning of the first line of the file instead of creating a new line. The terminal also throws an error if I try to put it all on the same line ("1i\": extra characters after \ at the end of i command).
Input :
1 2 3 4
1 2 3 4
1 2 3 4
Expected output
14
1 2 3 4
1 2 3 4
1 2 3 4
Upvotes: 1
Views: 2298
Reputation: 157947
Basially you are concatenating two files. A file containing one line and the original file. By it's name this is a task for cat
:
cat - file <<< 'new line'
# or
echo 'new line' | cat - file
while -
stands for stdin.
You can also use cat
together with command substitution if your shell supports this:
cat <(echo 'new line') file
Btw, with sed
it should be simply:
sed '1i\new line' file
Upvotes: 2
Reputation: 203149
$ sed '1i\14' file
14
1 2 3 4
1 2 3 4
1 2 3 4
but just use awk for clarity, simplicity, extensibility, robustness, portability, and every other desirable attribute of software:
$ awk 'NR==1{print "14"} {print}' file
14
1 2 3 4
1 2 3 4
1 2 3 4
Upvotes: 2