Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Shell 程式設計速查筆記:檔案測試、字串比較、數值運算、for 迴圈、sed 進階模式

編輯:Linux 教學

檔案測試運算子([ ... ] / [[ ... ]])

運算子真條件
-e FILE檔案存在
-f FILE一般檔案
-d FILE目錄
-L / -h FILE符號連結
-r/-w/-x FILE可讀/可寫/可執行
-s FILE大小非 0
-nt/-ot/-ef FILE1 FILE2FILE1 比 FILE2 新/舊/同一 inode
-z STRING字串長度為 0
-n STRING字串長度非 0
STRING1 = STRING2字串相等
STRING1 != STRING2字串不等
ARG1 -eq/-ne/-lt/-le/-gt/-ge ARG2整數比較

for 迴圈遍歷字串列表

SERVICES="80 22 25 110 8000 23 20 21 3306"
for port in $SERVICES; do
    iptables -A INPUT -p tcp --dport $port -m state --state NEW -j ACCEPT
done

利用 Shell 詞拆分(IFS)自動按空白切分,無需陣列語法。

sed 單行處理進階模式:只處理第一次匹配後進入死迴圈

sed '/abc/s/$/\nnew line/;ta;b;:a;n;ba' file
  • /abc/ 匹配含 abc 的行。
  • s/$/\nnew line/ 行尾插入新行。
  • ta:若替換成功跳轉標籤 :a。
  • b:無條件跳轉腳本結尾(跳過後續)。
  • :a 標籤;n 讀下一行;ba 跳回 :a 形成死迴圈,後續行不再處理。

效果:僅在第一個匹配行尾插入文字,後續匹配行忽略。

常用 sed 子命令速查

# 列印特定行
sed -n '2p' file           # 第 2 行
sed -n '1,3p' file         # 第 1-3 行
sed -n '$p' file           # 最後一行
sed -n '/pattern/p' file   # 匹配行

# 插入/附加新行
sed '/pattern/a\new line' file  # 匹配行後插入
sed '/pattern/i\new line' file  # 匹配行前插入
sed '5a\new line' file          # 第 5 行後插入

# 刪除
sed '1d' file           # 刪第 1 行
sed '1,3d' file         # 刪 1-3 行
sed '/pattern/d' file   # 刪匹配行
Copyright © Windows教程網 All Rights Reserved