如何使用包含文件中字段的字符串打印输出?

如何使用包含文件中字段的字符串打印输出?

假设我正在从名为“filename”的文件中查找包含“yellow”一词的行。然后我希望输出显示“衬衫的颜色是黄色”

假设我从文件“filename”中提取的行如下所示:

blue green orange black purple white yellow pink

我在想这样的事情,但我知道这是不对的:

cat filename | grep yellow | awk '{print $7; echo "The colour of the shirt is {$7}}

答案1

基本上,我在使用 grep 后得到了一行输出。然后我想输入该行的第 7 个字段并说“衬衫的颜色是“{第 7 个字段的输出}”

好吧,这对我来说更有意义。

要打印第七个字段以及字符串,请使用

awk '{ printf "The color is %s\n", $7 }'

或者

awk '{ print "The color is " $7 }'

(请注意,带引号的字符串和 之间没有逗号或加号或任何内容$7,字符串在 awk 中只需将它们写在彼此旁边即可连接起来。)

您也可以跳过grep并在内部执行等效操作awk

awk '/some regex/ { printf "the seventh field is %s\n", $7 }'

awk 接受的正则表达式与grep -E. (“大部分”,因为我不记得是否存在一些细微差别。)但您也可以将模式匹配指向特定字段:

awk '$3 ~ /regex for field three/ { printf "the seventh field is %s\n", $7 }'

当然它会处理所有匹配的行。愚蠢的例子:

$ awk '$1 ~ /^j/ { printf "the shirt of %s is %s\n", $1, $2 } ' < shirts
the shirt of jimmy is blue
the shirt of joe is red

答案2

awk ‘/yellow/ { print “The colour of the shirt is yellow” }’ < filename 

答案3

你可以做到这一切awk 正如杰夫所展示的,或者您可以在 shell 中轻松完成:

if grep -qF 'yellow' "filename"; then
    echo 'The colour of the shirt is yellow'
fi

在这里,-q停止grep输出任何内容(我们只对 的退出状态感兴趣grep)并-F告诉grep我们正在使用“固定字符串”(不是正则表达式)进行搜索。


如果您有一个内容为

[some unrelated data here]
shirt colour: yellow
[some unrelated shirt data here]

然后你可以使用

awk '/^shirt colour:/ { print "The colour of the shirt is", $NF }' filename

$NF...使用与给定正则表达式匹配的行的最后一个字段 ( ) 中的单词输出消息。

或者,

awk '/^shirt colour:/ { printf("The colour of the shirt is %s\n", $NF) }' filename

在最后两个示例中,您还可以使用$3(“第三个空格分隔字段”)代替$NF(“最后一个这样的字段”)。

相关内容