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 循环实现bash

#!/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
相关文章
相关标签/搜索