[英]how to know if awk command printed something without spoiling original output
我正在嘗試使用AWK命令,它為我打印得很好,我想要的確切方式
我的問題是,如果我使用的awk命令打印了一些沒有破壞的東西並改變它打印的方式,我怎么能從腳本中知道?
我使用的命令: gawk 'BEGIN{RS=ORS="\\n\\n" {s=tolower($0)} s~/word1|word2/' input_file.log
我試過了:
status=gawk 'BEGIN{RS=ORS="\\n\\n" {s=tolower($0)} s~/word1|word2/' input_file.log
if [ -z $status]
then
//status is empty or null, means nothing printed in awk command
echo "nothing"
else
//printed something in awk command
echo $status
問題是echo $status
按順序打印所有行,而行之間沒有“新行”
如何從awk打印原始打印而不會破壞它?
示例:輸入文件:
line 0 no words in here
line 1 starting
line 1 word1
line 2 no words here as well
line 3 starting
line 3 word2
line 3 end
line 4 nothing
line 5 nothing
命令: gawk 'BEGIN{RS=ORS="\\n\\n" {s=tolower($0)} s~/word1|word2/' input_file.log
預期產量:
line 1 starting
line 1 word1
line 3 starting
line 3 word2
line 3 end
如果我使用: stat=$(gawk 'BEGIN{RS=ORS="\\n\\n" {s=tolower($0)} s~/word1|word2/' input_file.log)
echo $stat
我得到輸出:
line 1 starting line 1 word1 line 3 starting line 3 word2 line 3 end
提前致謝!
不完全確定,因為你沒有顯示任何示例Input_file或預期輸出,所以你可以嘗試使用echo "$status"
。
編輯:由於您現在已經編輯了您的帖子,因此您應該將代碼更改為關注,然后應該飛行。
status=$(awk 'BEGIN{RS=ORS="\n\n"} {s=tolower($0)} s~/word1|word2/' Input_file)
if [[ -z $status ]]
then
echo "nothing"
else
echo "$status"
fi
您可以使用exit
代碼檢查awk
是否已打印某些內容
糾正你的代碼
從
gawk 'BEGIN{RS=ORS="\n\n" {s=tolower($0)} s~/word1|word2/' input_file.log
至
status=$(gawk 'BEGIN{RS=ORS="\n\n"}tolower($0)~/word1|word2/' input_file.log)
和(帶引號)
echo "$status"
發生這種情況是因為當您引用參數時(無論該參數是否傳遞給
echo
,test
或其他命令),該參數的值將作為一個值發送到命令。 如果你不引用它,那么shell會查找空格來確定每個參數的開始和結束位置。
糾正現有代碼
#!/usr/bin/env bash
status=$(gawk 'BEGIN{RS=ORS="\n\n"}tolower($0)~/word1|word2/' input_file.log)
if [ -z "$status" ]; then
echo "looks like nothing matched and so nothing printed"
else
echo "awk matched regex and printed something"
fi
這是用於檢查awk是否使用退出代碼打印了一些內容的代碼:
gawk 'BEGIN{RS=ORS="\n\n"}f=(tolower($0)~/word1|word2/){e=1}f; END{exit !e}' input_file.log
# check exit code
if [ "$?" -eq 0 ]; then
echo "awk matched regex and printed something"
else
echo "looks like nothing matched and so nothing printed"
fi
檢測結果:
$ cat test.sh
#!/usr/bin/env bash
gawk 'BEGIN{RS=ORS="\n\n"}f=(tolower($0)~/word1|word2/){e=1}f; END{exit !e}' "$1"
if [ "$?" -eq 0 ]; then
echo "awk matched regex and printed something"
else
echo "looks like nothing matched and so nothing printed"
fi
用於測試的示例文件
$ echo 'word1' >file1
$ echo 'nothing' >file2
文件內容
$ cat file1
word1
$ cat file2
nothing
用第一個文件執行
$ bash test.sh file1
word1
awk matched regex and printed something
用第二個文件執行
$ bash test.sh file2
looks like nothing matched and so nothing printed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.