[英]Parsing Command Output in Bash Script
我想運行一個命令,提供以下輸出並解析它:
[VDB VIEW]
[VDB] vhctest
[BACKEND] domain.computername: ENABLED:RW:CONSISTENT
[BACKEND] domain.computername: ENABLED:RW:CONSISTENT
...
我只對一些關鍵作品感興趣,例如'ENABLED'等。我不能只搜索ENABLED,因為我需要一次解析每一行。
這是我的第一個腳本,我想知道是否有人可以幫助我?
編輯:我現在有:
cmdout=`mycommand`
while read -r line
do
#check for key words in $line
done < $cmdout
我認為這樣做了我想要的但是它似乎總是在命令輸出之前輸出以下內容。
./myscript.sh:29:無法打開...:沒有這樣的文件
我不想寫一個文件來實現這一點。
這是psudo代碼:
cmdout=`mycommand`
loop each line in $cmdout
if line contains $1
if line contains $2
output 1
else
output 0
錯誤的原因是
done < $cmdout
認為$cmdout
的內容是文件名。
你可以這樣做:
done <<< $cmdout
要么
done <<EOF
$cmdout
EOF
要么
done < <(mycommand) # without using the variable at all
要么
done <<< $(mycommand)
要么
done <<EOF
$(mycommand)
EOF
要么
mycommand | while
...
done
但是,最后一個創建一個子shell,當循環退出時,循環中設置的任何變量都將丟失。
$ cat test.sh
#!/bin/bash
while read line ; do
if [ `echo $line|grep "$1" | wc -l` != 0 ]; then
if [ `echo $line|grep "$2" | wc -l` != 0 ]; then
echo "output 1"
else
echo "output 0"
fi
fi
done
用法
$ cat in.txt | ./test.sh ENABLED RW
output 1
output 1
這不是最好的解決方案,但是它可以逐字逐字地翻譯你想要的東西,並且應該給你一些開始並添加你自己的邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.