I am trying to compare two csv files. I want the line numbers to be stored into shell variables or array.
I tried something like this:
paste <(awk -F, '{print NR,$1}' file1) <(awk -F, '{print $1}' file2) | awk -v var=0 '{ print (($2==$3)?"match":"a[var]="$1); var++}' This didn't work. Moreover 'a' is not a shell variable here. How to proceed with this? Also suggest other ways of doing it.
Thanks in advance
31 Answer
Solution:
With awk print only line numbers where there are differences and collect them all in a bash array. Instead of using NR in the first awk subcommand, use NR in the last awk command:
line_numbers=($(\ paste \ <(awk -F, '{print $1}' file1) \ <(awk -F, '{print $1}' file2) \ | awk '{if ($1 != $2) print NR}' \ )) echo "Length: ${#line_numbers[*]}" for index in ${!line_numbers[@]}; do echo "line_numbers[$index] = ${line_numbers[index]}" done Example:
> awk '{print NR": "$0}' file1 1: aab 2: b 3: bcbaa 4: ab 5: bb 6: ca 7: ba 8: abacb 9: bccaba > awk '{print NR": "$0}' file2 1: aab 2: z 3: bcbaa 4: yyz 5: y 6: yx 7: ba 8: abacb 9: z > bash main.bash Length: 5 line_numbers[0] = 2 line_numbers[1] = 4 line_numbers[2] = 5 line_numbers[3] = 6 line_numbers[4] = 9