Linux学习总结(六十八)文本编辑脚本

有时候我们要借助脚本来编辑文本,请看下面的题目。
题目要求:
在文本文档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/bash
n=0
cat 1.txt |while read line
do
    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
    fi
done
\mv 2.txt 1.txt

猜你喜欢

转载自blog.51cto.com/12606610/2136297
今日推荐