1. 程式人生 > >Linux學習總結(六十八)文本編輯腳本

Linux學習總結(六十八)文本編輯腳本

追加 else 直接 另一個 then 總結 定向 結束 into

有時候我們要借助腳本來編輯文本,請看下面的題目。
題目要求:
在文本文檔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

Linux學習總結(六十八)文本編輯腳本