firstline secondline thirdline
...some magic happens here... :)
insertedtextfirstline secondline thirdline
Question: How can I insert the insertedtext to the start of the first line in a file?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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
zsh but not
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.