Input:
firstline secondline thirdline ...some magic happens here... :)
Output:
insertedtextfirstline secondline thirdline Question: How can I insert the insertedtext to the start of the first line in a file?
Input:
firstline secondline thirdline ...some magic happens here... :)
Output:
insertedtextfirstline secondline thirdline Question: How can I insert the insertedtext to the start of the first line in a file?
With GNU sed:
sed -i '1s/^/insertedtext/' file This replaces the beginning of the first line with the inserted text. -i replaces the text in file rather than sending the modified text to the standard output.
If portability across unices is a concern, use ed:
ed file <<END 1s/^/insertedtext/ w q END POSIX one:
$ { printf %s insertedtext; cat <./input_file; } >/tmp/output_file $ mv -- /tmp/output_file ./input_file sed, ed or ex). Another variation - not more or less correct, just a matter of taste:
awk 'BEGIN{printf "insertedtext"};{print $0}' file1.txt > file2.txt GNU sed will do.
sed -i '1s/\(.*\)/insertedtext\1/' However, note that appending at the beginning of the file requires rewriting of its whole content. In case of small files it is not a problem, but if the file in question has several dozens of gigabytes, then it might become a tricky task to do it efficiently.
In such cases you usually want to make some dirty tricks, like ensuring that the replacement text has exactly the same length as the original one, and just modify the selected bytes in-place.
<<IN head -n-1 >textfile insertedtext$( cat <textfile printf \\n.) IN In those shells which handle heredocuments with tempfiles (to include bash and zsh but not dash, busybox, or yash) the above command will safely overwrite the whole of textfile with itself and include the prepended string. The trailing \n. is added to preserve any trailing blanklines in textfile - which would otherwise be stripped by the command substitution.