7

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?

1
  • 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? Commented Jun 8, 2015 at 9:48

7 Answers 7

12

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.

0
7

If portability across unices is a concern, use ed:

ed file <<END 1s/^/insertedtext/ w q END 
0
5

POSIX one:

$ { printf %s insertedtext; cat <./input_file; } >/tmp/output_file $ mv -- /tmp/output_file ./input_file 
1
  • This is the fastest method (compared to sed, ed or ex). Commented Jun 8, 2015 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
  • 1
    gorkypl has a point. If you have a large document with multiple first line situations, you might to invest in a proper code. Commented Jun 8, 2015 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.

2
  • This one removed all trailing newlines of infile. Commented Jun 8, 2015 at 18:48
  • @cuonglm - good point. Commented Jun 8, 2015 at 22:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.