2012-05-27 28 views
1

我有一個文件:AWK - 如何用gsub改進這個例子?

one one one 
one one 
one one 
one 
one 
one 

此命令取代5次 「一」, 「三化」

$ awk '{for(i=1; NF>=i; i++)if($i~/one/)a++}{if(a<=5) gsub("one", "three"); print }' file 

three three three 
three three 
one one 
one 
one 
one 

現在,同樣的事情,但6次:

$ awk '{for(i=1; NF>=i; i++)if($i~/one/)a++}{if(a<=6) gsub("one", "three"); print }' file 

three three three 
three three 
one one 
one 
one 
one 

如何改進上面的例子?我想要這個結果:

three three three 
three three 
three one 
one 
one 
one 

謝謝你的幫忙。

回答

3
awk '{for (i=1; i<=NF; i++) {if ($i ~ /one/) {a++; if(a <= 6) sub("one", "three", $i)}}; print}' 
+0

我有一個問題。是否有必要使用上面的例子,寫'sub(「one」,「three」,$ i)' 而不是: 'sub(「one」,「three」)'? 謝謝。 – Tedee12345

+0

@ Tedee12345:如果你不指定字段(或其他變量),默認情況下使用$ 0。 'sub()'只會替換第一個實例,所以你不會在第二行使用默認的$ 0來得到「three」。 'gsub()'默認爲'$ 0',不會讓你在第三行有「三個」,因爲它會給你「三三個」,因爲它是全局的。你仍然可以像這樣使用'gsub':'gsub(「one」,「three」,1)'如果你想「oneoneone one」成爲「threethreethree one」,因爲「全局」只適用於字段1。 –

+0

否則,對於簡單的替換(因爲它出現在你的問題中,你根本不需要'sub'或'gsub'),你可以直接賦值'if(a <= 6) {$ i =「three」}' –