2016-02-04 49 views
3

後,我有一個文件a.text:AWK - 打印完整的輸入字符串比較

hello world 
my world 
hello universe 

我想打印完整的字符串,如果第二個字是「世界」:

[[email protected]:/var/log] cat a | awk -F " " '{if($2=="world") print $1}' 
hello 
my 

但我想要的輸出是:

[[email protected]:/var/log] cat a | awk -F " " '{if($2=="world") print <Something here>}' 
hello world 
my world 

任何關於如何做到這一點的指針?

在此先感謝。

+0

我只想在第二個元素是「世界」時打印完整的輸入行。 –

回答

1

如果你想/必須使用awk來解決問題:

awk '$0~/world/' file.txt 

如果某行(即$0)字符串「世界」匹配(即~/world/)全線打印

如果你只是想檢查第二列world

awk '$2 == "world"' file.txt 
+0

你不需要'$ 0〜/ world /'中的'$ 0〜',只需'/ world /'就足夠了。 –

+1

@EdMorton謝謝你的提示!我無法想象還有更短的解決方案 –

2
awk '{if ($2=="world") {print}}' file 

輸出:

 
hello world 
my world 
2

首先,因爲你正在編寫一個if語句,你可以使用awk 'filter{commands;}'模式,像這樣

awk -F " " '$2=="world" { print <Something here> }' 

要打印整個線就可以使用print $0

awk -F " " '$2=="world"{print $0}' file 

它可以寫成

awk -F " " '$2=="world"{print}' file 

{print}是默認操作,所以它可以像這樣的過濾器後,可以省略:

awk -F " " '$2=="world"' file 

甚至不帶-f選項,因爲空間是默認值FS

awk '$2=="world"' file