문제

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).

도움이 되었습니까?

해결책

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

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

다른 팁

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' *
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top