本文共 642 字,大约阅读时间需要 2 分钟。
有时候我们要借助脚本来编辑文本,请看下面的题目。
题目要求:在文本文档1.txt第五行(假设文件行数大于5)后面增加如下两行内容:# This is a test file.# Test insert line into this file.习题分析:方法一: 可以直接用sed -i 添加方法二:依次按顺序打印前5行,然后打印要增加的行,再从文本第六行开始一直到结束依次打印剩余的行。可以把打印内容追加重定向到另一个文本,再强制重命名即可。1 sed 直接实现sed -i "5a # This is a test file.\n# Test insert line into this file." 1.txt
2 循环实现 #!/bin/bashn=0cat 1.txt |while read linedo n=$[$n+1] if [ $n -eq 5 ];then echo $line >> 2.txt echo -e "# this is a test file.\n# test insert line into this file." >> 2.txt else echo $line >> 2.txt fidone\mv 2.txt 1.txt
转载于:https://blog.51cto.com/12606610/2136297