TransWikia.com

how to compare current line with next line in a csv and display the column difference in unix scripting

Unix & Linux Asked by Chitra Devi on December 24, 2021

file.csv

ABC,EFG,22  
XYZ,MNO,24  
XYZ,MNO,228
SPOT,ID,NUMBER
SPOT,ID,VARCHAR2
INF,SUMMARY,VARCHAR2
INF,SUMMARY,NUMBER

I want to compare first line with second line and display ABC and XYZ are different and second and third line comparison should bring 24 is the old value and 228 is the new value

Similar comparison of column wise if its different then print the values.
I have trouble in comparing current row with previous record

I am able compare for the same line. Below worked for me to some extent on the same row but to check for previous row i couldn’t.

awk -F: '{if(!($1==$2||$2==$3||$3==$1))printf("%s","not ");print"matched",$0}' file.csv

i also tried with while loop for reading and comparing by assigning the value to another variable.

x=""
while IFS= , read -r a b c
do
 if [a == x]]
then
 echo "$a"
x=$a
done < input.csv

One Answer

$ cat tst.awk
BEGIN { FS="," }
NR > 1 {
    if (p[0] != $0) {
        printf "nLine %d (%s) != %d (%s)n", NR-1, p[0], NR, $0
    }
    for (i=1; i<=NF; i++) {
        if (p[i] != $i) {
            printf "tField %d.%d (%s) != %d.%d (%s)n", NR-1, i, p[i], NR, i, $i
        }
    }
}
{ split($0,p); p[0]=$0 }

.

$ awk -f tst.awk file.csv

Line 1 (ABC,EFG,22) != 2 (XYZ,MNO,24)
        Field 1.1 (ABC) != 2.1 (XYZ)
        Field 1.2 (EFG) != 2.2 (MNO)
        Field 1.3 (22) != 2.3 (24)

Line 2 (XYZ,MNO,24) != 3 (XYZ,MNO,228)
        Field 2.3 (24) != 3.3 (228)

Line 3 (XYZ,MNO,228) != 4 (SPOT,ID,NUMBER)
        Field 3.1 (XYZ) != 4.1 (SPOT)
        Field 3.2 (MNO) != 4.2 (ID)
        Field 3.3 (228) != 4.3 (NUMBER)

Line 4 (SPOT,ID,NUMBER) != 5 (SPOT,ID,VARCHAR2)
        Field 4.3 (NUMBER) != 5.3 (VARCHAR2)

Line 5 (SPOT,ID,VARCHAR2) != 6 (INF,SUMMARY,VARCHAR2)
        Field 5.1 (SPOT) != 6.1 (INF)
        Field 5.2 (ID) != 6.2 (SUMMARY)

Line 6 (INF,SUMMARY,VARCHAR2) != 7 (INF,SUMMARY,NUMBER)
        Field 6.3 (VARCHAR2) != 7.3 (NUMBER)

Answered by Ed Morton on December 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP