我正在尝试使用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
提前致谢!
答案 0 :(得分:2)
不完全确定,因为您没有显示任何示例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
答案 1 :(得分:1)
您可以使用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