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

血红的双手。 提交于 2019-11-28 16:42:05

问题


This question already has an answer here:

  • Insert a line at specific line number with sed or awk 8 answers

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.


回答1:


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.




回答2:


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




回答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.




回答4:


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



回答5:


perl -pi -e 'if($.==14){s/\n/\navatar\n/g}if(eof){$.=0}' MakeFile*


来源:https://stackoverflow.com/questions/15157659/add-text-to-file-at-certain-line-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!