Frage

everyone

I pass a line to awk with commas as field separator. I'd like awk to produce the output still using commas as separator. However awk changes commas to spaces.

echo "qwer,asdf,zxcv" | awk -F',' '{gsub("a","b",$2); print $0}'
qwer bsdf zxcv

Is there a way to make awk respect the separator character of the original input?

War es hilfreich?

Lösung 2

Define the OFS, that is, Output Field Separator:

$ echo "qwer,asdf,zxcv" | awk -F',' 'BEGIN{OFS=","}{gsub("a","b",$2); print $0}'
qwer,bsdf,zxcv

Note also that {print $0} can be skipped and -F also included in the BEGIN{} block:

$ echo "qwer,asdf,zxcv" | awk 'BEGIN{FS=OFS=","}{gsub("a","b",$2)} 1'
qwer,bsdf,zxcv

Giving a 1 we give a True condition that is evaluated as {print $0} as default.

Andere Tipps

You can do like this with awk

echo "qwer,asdf,zxcv" | awk -F, '{gsub("a","b",$2); print $0}' OFS=,
qwer,bsdf,zxcv
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top