Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk get the nextline

Tags:

bash

awk

i'm trying to use awk to format a file thats contains multiple line.
Contains of file:

ABC;0;1
ABC;0;0;10
ABC;0;2
EFG;0;1;15
HIJ;2;8;00
KLM;4;18;12
KLM;6;18;1200
KLM;10;18;14
KLM;1;18;15

result desired:

ABC;0;1;10;2
EFG;0;1;15
HIJ;2;8;00
KLM;4;18;12;1200;14;15

I am using the code below :

awk -F ";" '{
        ligne= ligne $0
        ma_var = $1
        {getline
        if($1 != ma_var){
            ligne= ligne "\n" $0
        }
        else {
        ligne= ligne";"NF
        }
        }   
}
END {
    print ligne
} ' ${FILE_IN} > ${FILE_OUT}

the objectif is to compare the first column of the next line to the first column the current line, if it matches then add the last column of the next line to the current line, and delete the next line, else print the next line.

Kind regards,

like image 457
Abdelilah Avatar asked Oct 24 '25 19:10

Abdelilah


2 Answers

As with life, it's a lot easier to make decisions based on what has happened (the previous line) than what will happen (the next line). Re-state your requirements as the objective is to compare the first column of the current line to the first column the previous line, if it matches then add the last column of the current line to the previous line, and delete the current line, else print the current line. and the code to implement it becomes relatively straight-forward:

$ cat tst.awk
BEGIN { FS=OFS=";" }
$1 == p1 { prev = prev OFS $NF; next }
{ if (NR>1) print prev; prev=$0; p1=$1 }
END { print prev }

$ awk -f tst.awk file
ABC;0;1;10;2
EFG;0;1;15
HIJ;2;8;00
KLM;4;18;12;1200;14;15

If you're ever tempted to use getline again, be sure you fully understand everything discussed at http://awk.freeshell.org/AllAboutGetline before making a decision.

like image 173
Ed Morton Avatar answered Oct 26 '25 08:10

Ed Morton


I would take a slightly different approach than Ed:

 $ awk '$1 == p { printf ";%s", $NF; next } NR > 1 { print "" } {p=$1; 
    printf "%s" , $0} END{print ""}' FS=\; input

At each line, check if the first column matches the previous. If it does, just print the last field. If it doesn't, print the whole line with no trailing newline.

like image 44
William Pursell Avatar answered Oct 26 '25 09:10

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!