嘗試從 txt 中的字串 grep 正則運算式并回顯狀態。.txt 看起來像這樣:
something something something name1 something something Available something something something
something something something name2 something something Available something something something
something something something name3 something something Available something something something
something something something name4 something something No status something something something
something something something name5 something something No status something something something
我能夠在第一行找到模式并回顯狀態
cat status.txt | grep -o $name>/dev/null ; cat status.txt | grep -o "No status">/dev/null && echo $name is offline || echo $name is online
name1 is online
這作業正常;但是我將如何在所有線路上進行這項作業,以便我得到
name1 is online
name2 is online
name3 is online
name4 is offline
name5 is offline
我上下看了看,無法弄清楚這一點。我也嘗試過 sed 和 awk 的變體。沒有任何作用。也許我應該為此使用python或其他東西。謝謝你的幫助!
uj5u.com熱心網友回復:
使用 awk
$ awk '{if ($7 == "Available") print $4 " is online"; else print $4 " is offline"}' status.txt
name1 is online
name2 is online
name3 is online
name4 is offline
name5 is offline
uj5u.com熱心網友回復:
不要grep用于這個。逐行讀取檔案,從中提取您需要的資訊。
while read -r x y z name rest; do
case "$rest" in
*Available*) printf '%s is online\n' "$name" ;;
*"No status"*) printf '%s is offline\n' "$name ;;
esac
done < status.txt
uj5u.com熱心網友回復:
基于第七個欄位使用三進制控制輸出的類似awk實作可以寫成:
awk '{print $4 " is " ($7=="Available" ? "online" : "offline")}' file
示例使用/輸出
使用您的資料file,您將擁有:
$ awk '{print $4 " is " ($7=="Available" ? "online" : "offline")}' file
name1 is online
name2 is online
name3 is online
name4 is offline
name5 is offline
您的方法存在問題
您的方法存在許多相同的低效率,特別是當您這樣做時:
cat status.txt | grep -o ...; cat status.txt | grep -o ...
您連續提交兩個UUOc。除非您連接兩個(或更多)檔案,否則cat file是不必要的cat(UUOc)使用,應避免使用。相反,只需讀取檔案或使用重定向。例如:
grep -o ... status.txt; grep -o ... status.txt ...
每個管道'|'生成一個單獨的子shell,以將一個行程的輸出 ( stdout) 與下一個行程的輸入 ( stdin) 聯系起來。沒有cat必要grep。grep可以直接讀取檔案或stdin通過重定向讀取檔案,例如grep ... file或grep ... < file.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467905.html
