[英]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.