5

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?

  • Do you have to enter only at the first line of the file, or this first line at different sections of the file, for example, paragraphs? – bbh Jun 8 '15 at 9:48
8

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.

7

If portability across unices is a concern, use ed:

ed file <<END
1s/^/insertedtext/
w
q
END
  • 1
    +1 for the use of ed(1). :) – lcd047 Jun 8 '15 at 17:55
5

POSIX one:

$ { printf %s insertedtext; cat <./input_file; } >/tmp/output_file
$ mv -- /tmp/output_file ./input_file
  • This is the fastest method (compared to sed, ed or ex). – dan Jun 8 '15 at 17:43
4

In perl

perl -pi -e 's/^/insertedtext/ if $.==1' myfile.txt
3

Another variation - not more or less correct, just a matter of taste:

awk 'BEGIN{printf "insertedtext"};{print $0}' file1.txt > file2.txt
2

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.

  • 1
    gorkypl has a point. If you have a large document with multiple first line situations, you might to invest in a proper code. – bbh Jun 8 '15 at 9:50
0
<<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.

  • This one removed all trailing newlines of infile. – cuonglm Jun 8 '15 at 18:48
  • @cuonglm - good point. – mikeserv Jun 8 '15 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.