0

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?

3
  • 1
    but I got: I run your code as is and I got only f4 printed twice. Can't reproduce.. Commented Jun 24, 2021 at 6:30
  • I can reproduce the output when I remove the echo $_NEW and add a non-printable character (e.g. $'\x01') before the f3 in test_new. Commented Jun 24, 2021 at 7:02
  • I only get f4 displayed twice. If you remove echo $F_NEW I get the expected output f4 Commented Jun 24, 2021 at 7:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If loop is long,I tried awk 'NR==FNR { arr[$1]=1;next } arr[$1] != "1" { added+= $1 }' test test_new printf '%s\n' "${added[@]}" but there's no output.what's the problem?
try readarray -t added <<< "$(awk 'NR==FNR { arr[$1]=1;next } arr[$1] != "1" { added+= $1 }' test test_new)";printf '%s\n' "${added[@]}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.