Add text to file at certain line in Linux [duplica

2020-02-16 08:44发布

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.

5条回答
看我几分像从前
2楼-- · 2020-02-16 09:09

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.

查看更多
祖国的老花朵
3楼-- · 2020-02-16 09:09

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

查看更多
萌系小妹纸
4楼-- · 2020-02-16 09:09

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楼-- · 2020-02-16 09:18
perl -pi -e 'if($.==14){s/\n/\navatar\n/g}if(eof){$.=0}' MakeFile*
查看更多
走好不送
6楼-- · 2020-02-16 09:28

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.

查看更多
登录 后发表回答