19

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.

Damien
  • 375
  • 1
    I believe sed is not the correct tool for this (it doesn't understand columns). You are right in using awk. – gardenhead Jan 01 '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 'SO- stop being evil' Jan 01 '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 02 '16 at 05:24

2 Answers2

22

@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
Wildcard
  • 36,499
17

You can set the Output Field Separator, OFS.

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

Or:

'BEGIN { OFS = FS } ...'

It is <space> by default.

Runium
  • 28,811