Question

I have a text file which has 5 columns separated by commas as follows

449,615,43,57,8
308,617,43,57,3
345,558,43,57,11

However a bug was identified in the code which generates these files and now i need to update the last column of the files such that

if i > 10 i = i + 1 else i

I have never used awk and sed but I got the impression that this should be trivial using those tools. Can anyone give me some pointers for this? Thanks

Edit: Expected output for above:

449,615,43,57,8
308,617,43,57,3
345,558,43,57,12
Was it helpful?

Solution

Using awk:

awk 'BEGIN{FS=OFS=","}{$NF=($NF>10?$NF+1:$NF)}1' file

$ cat file
449,615,43,57,8
308,617,43,57,3
345,558,43,57,11
$ awk 'BEGIN{FS=OFS=","}{$NF=($NF>10?$NF+1:$NF)}1' file
449,615,43,57,8
308,617,43,57,3
345,558,43,57,12

Can be reduced to as suggested by anubhava in comments:

$ awk 'BEGIN{FS=OFS=","} $NF>10{$NF++} 1' file
449,615,43,57,8
308,617,43,57,3
345,558,43,57,12

OTHER TIPS

oneliner:

awk -F, -v OFS="," '{$NF+=$NF>10}7' 

test

kent$  echo "449,615,43,57,8
308,617,43,57,3
345,558,43,57,11"|awk -F, -v OFS="," '{$NF+=$NF>10}7'   
449,615,43,57,8
308,617,43,57,3
345,558,43,57,12
awk -F, -v OFS="," '{if($5>10)$5=$5+1}1' input.txt

Output:

449,615,43,57,8
308,617,43,57,3
345,558,43,57,12
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top