kittygirl
kittygirl

Reputation: 2443

Defined variable in bash loop cannot be compared correctly

Creat 2 files at first:

cat <<'EOF'> test
f u u 1624268497
f3 u2 u2 1624268498
EOF


cat <<'EOF'> test_new
f u4 u5 16242684973
f4 u2 u2 1624268498
f3 u2 u2 1624268498
EOF

I want to loop files to list the unique element of test_new,script as below:

##!/bin/bash
added=()
while read F_NEW O_NEW G_NEW P_NEW; do
    exist=0
    while read F O G P; do
    #exist in both old & new
    if [[ $F_NEW == $F ]]; then
        exist=1
        break
    fi
    #   echo "tester: $F"
    done < test
    if [ $exist == 0 ]; then
    echo $F_NEW
        added+=($F_NEW)
    fi

done < test_new

printf '%s\n' "${added[*]}"

Expect result is:

f4

but I got:

f4 f3

Where is the problem?

Upvotes: 0

Views: 53

Answers (1)

Raman Sailopal
Raman Sailopal

Reputation: 12877

Awk is a good candidate for a problem such as this:

awk 'NR==FNR { arr[$1]=1;next } arr[$1] != "1" { print $1 }' test test_new

Process the test file first (NR==FNR) Create an array called arr keyed by the first space delimited field. Then when processing the test_new file, if there isn't an entry in arr for the first field, print the first field.

Upvotes: 1

Related Questions