Frage

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

War es hilfreich?

Lösung

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

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

Andere Tipps

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' *
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top