user6008947
user6008947

Reputation: 13

Can you print to a specific column in awk?

I've begun doing things in awk for file comparisons. Is there a way to print data to a specific column? The book I am using does not touch upon this in the print section and I can't seem to find exactly what I am looking for.

Let's say I wanted to print a line, but also print a string ("test") inside of a specific blank column[$12]. Can I do that? Thanks for any help

{print $0, "test"[$12]}

Upvotes: 1

Views: 95

Answers (1)

karakfa
karakfa

Reputation: 67467

you can overwrite existing fields easily

$ awk '... {$12="test"; print}' file

if you have your code and sample input output people can suggest better ways since usually what you ask for is not what you really need.

e.g.

$ echo 'a,b,c, ,e' | awk -F, -v OFS=, '{$4="test"; print}'

a,b,c,test,e

awk will also extend (add missing fields) if add to an index higher than what you currently have

$ echo 'a,b,c, ,e' | awk -F, -v OFS=, '{$12="test"; print}'

a,b,c, ,e,,,,,,,test

also you can shorten the code by replacing print with 1, such as

... '{$4="test"}1'

Upvotes: 3

Related Questions