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
Related videos on Youtube
Author by
LoukiosValentine79
Updated on September 18, 2022Comments
-
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 almost 9 yearsDo 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 almost 9 yearsgorkypl has a point. If you have a large document with multiple first line situations, you might to invest in a proper code.
-
dan almost 9 yearsThis is the fastest method (compared to
sed
,ed
orex
). -
lcd047 almost 9 years+1 for the use of
ed(1)
. :) -
cuonglm almost 9 yearsThis one removed all trailing newlines of
infile
. -
mikeserv almost 9 years@cuonglm - good point.