Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text to file at certain line in Linux [duplicate]

I want to add a specific line, lets say avatar to the files that starts with MakeFile and avatar should be added to the 15th line in the file.

This is how to add text to files:

echo 'avatar' >> MakeFile.websvc

and this is how to add text to files that starts with MakeFile I think:

echo 'avatar' >> *MakeFile.

But I can not manage to add this line to the 15th line of the file.

like image 712
user2123459 Avatar asked Mar 01 '13 12:03

user2123459


People also ask

How do I add text to a line in Linux?

Append Text Using >> Operator Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.

How do you add text to a file with multiple names in Linux?

you can simply: echo "my text" | tee -a file1. txt file2. txt . No need to pipe to a second tee.


3 Answers

You can use sed to solve this:

sed "15i avatar" Makefile.txt

or use the -i option to save the changes made to the file.

sed -i "15i avatar" Makefile.txt

To change all the files beginning that start Makefile:

sed "15i avatar" Makefile*

Note: In the above 15 is your line of interest to place the text.

like image 97
Sunil Bojanapally Avatar answered Oct 20 '22 06:10

Sunil Bojanapally


Using sed :

sed -i '15i\avatar\' Makefile*

where the -i option indicates that transformation occurs in-place (which is useful for instance when you want to process several files).

Also, in your question, *MakeFile stands for 'all files that end with MakeFile', while 'all files that begin with MakeFile' would be denoted as MakeFile*.

like image 43
lmsteffan Avatar answered Oct 20 '22 06:10

lmsteffan


If you need to pass in the string and the line-number options to the script, try this:

perl -i -slpe 'print $s if $. == $n; $. = 0 if eof' -- -n=15 -s="avatar" Makefile*

-i edit the input file, do not make a backup copy
$. is the line number

This is based on my solution to Insert a line at specific line number with sed or awk, which contains several other methods of passing options to Perl, as well as explanations of the command line options.

like image 3
Chris Koknat Avatar answered Oct 20 '22 04:10

Chris Koknat