52

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.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
user2123459
  • 523
  • 1
  • 4
  • 6
  • The second example is wrong. You need to loop through files and add a line to each file individually. If you want to add text in the middle of a file, you need to loop through the file's contents and insert your stuff when you reach the right place. – n. m. could be an AI Mar 01 '13 at 12:28

5 Answers5

95

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.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
3

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*.

lmsteffan
  • 840
  • 4
  • 13
3

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.

Community
  • 1
  • 1
Chris Koknat
  • 3,305
  • 2
  • 29
  • 30
2

If you want a more portable version, you can use ex, which will work on any *Nix system. (It's specified by POSIX.) The Sed commands given so far depend on GNU Sed.

To insert a line containing nothing but "avatar" at the 15th line of each file in the current directory whose name begins with "Makefile.", use:

for f in MakeFile.*; do printf '%s\n' 15i 'avatar' . x | ex "$f"; done
Wildcard
  • 1,302
  • 2
  • 20
  • 42
1
perl -pi -e 'if($.==14){s/\n/\navatar\n/g}if(eof){$.=0}' MakeFile*
Vijay
  • 65,327
  • 90
  • 227
  • 319