Insert a word in the first line of the file

7,077

Solution 1

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.

Solution 2

If portability across unices is a concern, use ed:

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

Solution 3

POSIX one:

$ { printf %s insertedtext; cat <./input_file; } >/tmp/output_file
$ mv -- /tmp/output_file ./input_file

Solution 4

In perl

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

Solution 5

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

awk 'BEGIN{printf "insertedtext"};{print $0}' file1.txt > file2.txt
Share:
7,077

Related videos on Youtube

LoukiosValentine79
Author by

LoukiosValentine79

Updated on September 18, 2022

Comments

  • LoukiosValentine79
    LoukiosValentine79 over 1 year

    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?

    • Admin
      Admin almost 9 years
      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?
  • John Pretak
    John Pretak almost 9 years
    gorkypl has a point. If you have a large document with multiple first line situations, you might to invest in a proper code.
  • dan
    dan almost 9 years
    This is the fastest method (compared to sed, ed or ex).
  • lcd047
    lcd047 almost 9 years
    +1 for the use of ed(1). :)
  • cuonglm
    cuonglm almost 9 years
    This one removed all trailing newlines of infile.
  • mikeserv
    mikeserv almost 9 years
    @cuonglm - good point.