12

This question already has an answer here:

I try to modify one column of my file, then print the result.

awk -F"|" '{ if(NR!=1){$5 = $5+0.1} print $0}' myfile

It does what I want, but when printing, only the first line keeps its field separator.( the one, i don't modify).

So I could use print $1"|"$2"|"$3"|"$4"|"$5"|"... but isn't there a solution using $0 ? (For example if I don't know the numbers of column)

I believe, I could solve my problem easily with sed, but I try to learn awk for now.

marked as duplicate by muru, Scott, Michael Homer, Anthon, Community Jan 2 '16 at 9:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    I believe sed is not the correct tool for this (it doesn't understand columns). You are right in using awk. – gardenhead Jan 1 '16 at 21:45
  • 2
    Please do not edit your question to reply to answers. To thank the answerers, upvote their answer (assuming they're correct and helpful of course), and accept the one that best solves your problem (or none, if none is fully satisfactory). For more information, see the help center. – Gilles Jan 1 '16 at 23:56
  • 4
    @gardenhead, not only does sed not understand columns, it also doesn't understand numbers at all. It is purely for text. It would be extraordinarily difficult and hacky to set up a sed command to "add 0.1 to a number". :) – Wildcard Jan 2 '16 at 5:24
14

@Sukminder has already given the simple answer; I have a couple tidbits of style points and helpful syntax about your example code (like a code review). This started as a comment but it was getting long.

OFS is the output field separator, as already mentioned.

$0 is the default argument to print—no need to specify it explicitly. And another style point: awk has what's called "patterns", which are like built-in conditional blocks. So you could also just use:

awk -F'|' 'BEGIN {OFS = FS} NR != 1 {$5 += 0.1} {print}' myfile
  • 2
    And the default action for a true condition is print, so {print} is often condensed to 1. – muru Jan 2 '16 at 1:40
  • 1
    @muru, very true. I was going to mention it but was running out the door. :) – Wildcard Jan 2 '16 at 5:22
15

You can set the Output Field Separator, OFS.

'BEGIN { OFS = "|" } ...'

Or:

'BEGIN { OFS = FS } ...'

It is <space> by default.

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