I have space separated file. I want to do some math operation on given column. e.g. I want to multiply column 2 by 1e6. I can use following command:

awk 'BEGIN { FS=","; OFS=","; } {print $1,$2=$2*1e6,$3,$4}' result.txt

My problem is my file may contain any number of columns. In this case, what should my awk command be? Let's say my file has 25 columns, and I want to multiply the 15th column by 100. How can I do this in awk?

  • I don't understand what the problem is. All you need is print $15*100. Please edit and clarify your problem. Can the file have different numbers of columns per line, so you don't always want to print $15? Is it that you don't know how to print the entire line without listing the fields? – terdon Aug 17 '16 at 15:00
  • awk '{$15 *= 100} 1' – Satō Katsura Aug 17 '16 at 15:01
  • @terdon I believe the question is how to deal with print $1, ... $NF when you don't know in advance the number of columns. – Satō Katsura Aug 17 '16 at 15:03
  • @SatoKatsura yes, it might be. Or it might be because the number of columns changes, let's see if the OP clarifies. In the meantime, you may as well post your comment as an answer if you like. – terdon Aug 17 '16 at 15:04
  • It's also confusing that the question title refers to a "space separated file" but the posted example uses FS="," – steeldriver Aug 17 '16 at 15:24

Instead of printing all the fields you can print the whole line with $0.

This can work because we can change fields by assigning data to them



will update the second field and leave the rest untouched:

% echo '1 2 3 4' | awk '{$2=$2*100; print $0}'
1 200 3 4

We can make this smaller by making use of defaults; eg print on its own will print $0

awk '{$2=$2*100; print}'

We can even make use of default actions:

awk '{$2=$2*100} 1'

But in general I recommend the longer version because it's easier for other people to read and understand; code maintainability is as important as conciseness:

awk '{$2=$2*100; print $0}'
| improve this answer | |

You don't need to know the number of columns, you can just update the one you need in place, and awk will reassemble them:

awk '{ $15 *= 100 } 1' file.csv

But you can also use NF if you need to, say like this:

awk '{ $15 *= 100; for(i=1; i<=NF; i++) printf(" %d", $i); print "\n" }' file.csv
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.