bash Awk - 如何剪切一条线,检查一列是否匹配某些内容,打印另一列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19047656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Awk - How to cut a line, check if a column matches something, print another column?
提问by ComputerFellow
I have a laaaaaargefile like this:
我有一个像这样的laaaaaarge文件:
VENDOR|QTY|ITEM|PRICE
2|3|Sugar|15
3|3|Coffee|35
4|244|Sugar2|55
33|2|Pizza|36
3|3|Pizza|55
5|5|Pizza2|33
6|6|Pizza3|44
How do I print VENDOR
and PRICE
IFFITEM
is Pizza
?
我如何打印VENDOR
和PRICE
IFFITEM
是Pizza
?
I've tried grep
but it's slow.
我试过了,grep
但是很慢。
I could write a python code like so,
我可以像这样写一个python代码,
for line in file:
fields = line.split('|')
if fields[2] == 'Pizza':
print fields[0], fields[-1]
but I want to do it in Awkfrom the shell itself. How do I do this?
但我想从 shell 本身用awk来做。我该怎么做呢?
Update
更新
How do I check substrings as well?
我如何检查子字符串?
I want to output VENDOR
and PRICE
if Pizzaoccurs in ITEM
?
我想输出VENDOR
,PRICE
如果Pizza出现在ITEM
?
Output should be:
输出应该是:
33|36
3|55
5|33
6|44
回答by fedorqui 'SO stop harming'
This makes it:
这使它:
$ awk -F\| '=="Pizza" {print ,}' file
33 36
3 55
Explanation
解释
-F\|
set|
as field delimiter.$3=="Pizza"
check if the 3rd field is "Pizza".{print $1,$4}
prints the 1st and 4th fields.
-F\|
设置|
为字段分隔符。$3=="Pizza"
检查第三个字段是否为“Pizza”。{print $1,$4}
打印第 1 个和第 4 个字段。
Update
更新
I want to output
VENDOR
andPRICE
if Pizzaoccurs inITEM
?
我想输出
VENDOR
,PRICE
如果Pizza出现在ITEM
?
$ awk 'BEGIN{OFS=FS="|"} ~/Pizza/ {print ,}' file
33|36
3|55
5|33
6|44
Explanation
解释
$3~/Pizza/
checks "occurs", as well as$3=="Pizza
checks exact matching.BEGIN{OFS=FS="|"}
sets the (input & output) field separator to be|
.
$3~/Pizza/
检查“发生”,以及$3=="Pizza
检查精确匹配。BEGIN{OFS=FS="|"}
将(输入和输出)字段分隔符设置为|
.