Hello!
I have the following lines in a file:
1|0|HEADER|
2|1|HEADER|
3|1|MAIN|
4|1|INFO|
5|1|INFO|
6|1|INFO|
7|2|INFO|
8|4|INFO|
9|55|FOOTER|
10|1|HEADER|
11|22|MAIN|
12|9|MAIN|
and I want to convert it into:
1|0|HEADER|
2|1|HEADER|
3|1|MAIN|
4|1|INFO|
5|1|INFO|
6|1|INFO|
7|1|INFO|
8|1|INFO|
9|1|FOOTER|
10|2|HEADER|
11|2|MAIN|
12|2|MAIN|
That is start second field with 0 populate next line's second field with that number and every time you find "HEADER" in the 3rd field increment that number.
This is what I managed so far:
awk 'BEGIN{OFS=FS="|"}{i=0;if($3=="HEADER"){i+=i}}$2{$2=i}{print > "temp"}' file
However it gives me the wrong result, it does increment the line where it finds "HEADER" but the next line it populates it with 0 again:
1|1|HEADER|
2|1|HEADER|
3|0|MAIN|
4|0|INFO|
5|0|INFO|
6|0|INFO|
7|0|INFO|
8|0|INFO|
9|0|FOOTER|
10|1|HEADER|
11|0|MAIN|
12|0|MAIN|
Any ideas would be much apreciated
upto my knowledge i have a solution.
remove the first field and sort the data according the second field.
after that add numbers.
regards
rajesh
Tha did not work, it jsut replaced all the numbers to 0 :wall:
I don't just need to sort the second field, I need to number it incrementing by 1 each time in the 3rd field there is a "HEADER"
so
1|0|MAIN
2|0|HEADER
3|0|INFO
4|0|FOOTER
5|0|HEADER
6|0|MAIN
would be:
1|0|MAIN
2|1|HEADER
3|1|INFO
4|1|FOOTER
5|2|HEADER
6|2|MAIN
regards
panyam
February 23, 2011, 9:59am
4
Does this help
awk -v c=0 -F"|" '/HEADER/ { $2=c;print ; prev=c ; c=c+1 ;next} {$2=prev;print}' OFS="|" input_file
nawk '$3=="HEADER" {$2=c++}1' FS='|' OFS='|' myFile
panyam
February 23, 2011, 10:11am
6
Hi vgersh99,
Your code does not work as the OP expected.
true, but the OP's description and the sample input/output contradict each other as well.
Given the 'description', here's the modified code:
nawk '$3=="HEADER" {$2=c++}$2=c' FS='|' OFS='|' myFile
This worked like a charm,
I amended the prints to append to a temp file
Thanks to everyone for your help