2013-02-06 29 views
0

我有這種格式的文本文件[ONE testing 1 2 3] [TWO lorem ipsum] [ONE 123]使用awk檢測正則表達式並按行打印?

我想逐行打印`[ONE。+]'。

一個例子輸出是

[ONE testing 1 2 3] 
[ONE 123] 

我試過awk '/\[ONE.+\]/ { print $1 }',但沒有奏效。任何人都可以教我爲什麼?那麼正確的方法是什麼?

回答

0

AWK通過線工作線,因此表達式僅每行一次匹配。要在awk中執行此操作,可以在循環中使用match函數。你還必須修改你的正則表達式,使其不那麼貪婪,因爲你的表達式並不會在第一次停止。

可能更容易只是使用grep:

echo "[ONE testing 1 2 3] [TWO lorem ipsum] [ONE 123]" | grep -o '\[ONE[^]]*\]' 
0

你可以嘗試這樣的

sed -re 's/(\[ONE[^\[]*\])/\n\1\n/g' temp.txt 

輸入的東西

[ONE testing 1 2 3] [TWO lorem ipsum] [ONE 123]

輸出

[ONE testing 1 2 3] 
[TWO lorem ipsum] 
[ONE 123] 

如果你想有兩個,然後

sed -re 's/(\[ONE[^\[]*\])()/\n\1\n/g; s/(\[[^ONE][^\[]*\])//g' temp.txt 

輸出

[ONE testing 1 2 3] 

[ONE 123] 
0

刪除列。如果這是更大的東西的一部分:

BEGIN { 
# Change the field-separator, from default blank, to the end-marker 
# for each "field" 
    FS = "] " 
} 
# Get rid of lines which can't possibly match 
!/\[ONE/ { next 
    } 
{ 
# Test and report each of three fields for starting with [ONE, 
# "closing" the field with FS, except for the last which will 
# already be "closed" 
if ($1 ~ /^\[ONE/) { 
    print $1 FS 
    } 
if ($2 ~ /^\[ONE/) { 
    print $2 FS 
    } 
if ($3 ~ /^\[ONE/) { 
    print $3 
    } 
} 

的「如果如果你有一個,可以用循環中的一個代替因爲不需要FS(字段分隔符)(除非數據中有空格)。

0

「AWK」默認取爲「單一空間」作爲分隔符和「打印$ 1」命令嘗試檢索由默認分離器分離的第一個值。

嘗試了這一點:

讓有一名爲包含三條線「的test.txt」的文本文件。

貓測試。TXT

[ONE測試1 2 3]

[TWO Lorem存有]

[ONE 123]

的grep -h '[ONE *' 的test.txt

[ONE測試1 2 3]

[ONE 123]