Wednesday, June 4, 2008

Modify last few fields : awk


Input File:


$ cat file.txt
MrA|1|2|3
MrB|4|5|6
MrC|7|8|9


Suppose I have to increment last two fields in file.txt by 10. i.e. required output:


MrA|1|12|13
MrB|4|15|16
MrC|7|18|19


The basic solution using awk:


$ awk '
BEGIN{OFS=FS="|"; inc=10}
{$NF=$NF+inc
$(NF-1)=$(NF-1)+inc} {print}
' file.txt


Now using awk function:

Making it more generic with a function f_inc. The function takes two args
1) Number of last fields to be incremented by 2)"inc" value


$ awk '
BEGIN { OFS=FS="|" }
function f_inc(f,inc) {
for (i=0; i<f; i++) {
$(NF-i)=$(NF-i)+inc;
}
}
{
f_inc(2,10);
print;
}
' file.txt


Output:


MrA|1|12|13
MrB|4|15|16
MrC|7|18|19

2 comments:

satish said...

hi friends can anyone solve this.


file1.csv
GJR10101315511000145,22093165,96734353,250,GJR,UER
HPR10101318071200662,57298772,03289112,250,HPR,DLR
HPR10101317581100059,57651616,02894754,250,HPR,DLR
HRR10101318031000352,02190237,03963371,250,HRR,DLR
HRR10101322141200125,02191868,03426983,250,HRR,DLR
HRR10101318071100028,02192292,77203779,250,HRR,BHR
KOR10101317231000008,04090878,14635365,250,KOR,WBR
KOR10101315171200004,04798063,14367284,250,KOR,WBR
KOR10101316291200024,13996348,97000215,250,KOR,BHR

file2.csv
KOR10101315511000150,57457784,250
GJR10101315511000145,96734353,250
UER10101315511000150,66734353,200
HRR10101315511000151,96734353,206
UER10101315511000164,96734353,200
UER10101319451200169,96734353,250
GJR10101315511000145,96734353,206
........
.n numbers.....
.......
GHR10101315511000150,36646466,200
HPR10101318071200662,03289112,250
HPR10101318071200662,03289112,206
DLR10101318071200664,03289112,206

OUTPUT:
FILE3.CSV
UER10101315511000164,96734353,200
DLR10101318071200664,03289112,206

Let me explain..
now i have to get column 1 removing first three character in file1.csv Eg:-like(10101315511000145) and add that 6th column to it like(UER10101315511000145).Now from 145 i have to increament+1 till 999 to it and compare column1 from file2 whichever number appears first it should display that line from file2.csv....so here i get UER10101315511000150 but 2nd colum doesnt matches to 3rd column in file1..so i have to go for next increament which matches that too.

thanks in advance

Unknown said...

@Satish,

Solution to first part of your problem will be something like this (if I understood it correctly)


#!/bin/sh

for line in $(sed 's/^.\{3\}//' file1.csv | awk -F "," 'BEGIN {OFS=","}{print $6$1,$2,$3}')
do
eval $(echo "$line" | awk -F "," '{print "A="$1";B="$2";C="$3}')
exceptlastthree=$(echo $A | sed 's/.\{3\}$//')
lastthree=$(echo $A | sed 's/^.*\(...\)$/\1/')
for i in $(seq $lastthree 999)
do
echo $exceptlastthree$i,$B,$C
done
done

© Jadu Saikia www.UNIXCL.com