awk change once per file

一世执手 提交于 2019-12-12 06:44:54

问题


awk -i inplace '
  BEGIN {FS=" "}
  BEGINFILE {changed=0} 
  { print;if ($1 == "namespace" && !changed) {print "foo";changed=1} }
' *

Is there a more elegant way to do this? Some built-in construct I missed? I am running GNU Awk 4.1.0 (and I am superb glad for -i inplace).


回答1:


awk -i inplace '$1=="namespace" && !seen[ARGIND]++ {$0=$0 ORS "foo"} 1' *

FS=" " is the default, no need to specify it explicitly.




回答2:


You could say:

... -F' ' '$1 == "namespace" && !a {$0=$0 RS "foo";a=1}1' file

or even:

... -F' ' '$1 == "namespace" && !_ {$0=$0 RS "foo";_=1}1' file

As mentioned in the comment above, this is pretty similar to what you've written except that it uses the RS variable to insert the text.


In order to do this for multiple files, you'd need to reset the variable:

... -F' ' 'BEGINFILE {a=0} $1 == "namespace" && !a {$0=$0 RS "foo";a=1}1' *

or

... -F' ' 'FNR==1 {a=0} $1 == "namespace" && !a {$0=$0 RS "foo";a=1}1' *


来源:https://stackoverflow.com/questions/20185553/awk-change-once-per-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!