I have a tab separated file with 16 fields. Can i use awk to conditionally alter one one or fields and print the whole line as the output? e.g., depending on value in the first field, i want to say add a specific number to field 4 and so on. But as a output i have to print the whole line. If yes, i would like to know how.
I have a tab separated file with 16 fields. Can i use awk to
Share
Yes, here’s an approach:
With etuardu’s sample file, this produces
Here’s how it works. There are two cases, expressed as awk patterns and actions. In the first, the pattern is a test of the first field to see if it equals
"ALTER", invoking the action that modifies the fifth field if the pattern evaluates to true. The second pattern is that final1; it’s always true, so the implicitprintaction is performed.One quirk with this solution: the field separators read in the input need not be those in the output. With the simple form above, the field separators from the inputs are taken to be whitespace, while single spaces are written to the output; set
FSandOFSto specific values if that isn’t what you want. However, only lines where a field is changed will have the new field separators, so a null op like ‘$1=$1’ will force all records to be rebuilt (this is a convenient way to change field separators, by only using$1=$1).