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

孤人 提交于 2019-11-29 20:37:05

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.

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

Chris Koknat

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.

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
perl -pi -e 'if($.==14){s/\n/\navatar\n/g}if(eof){$.=0}' MakeFile*
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!