1

I have two for loops here

for i in $(cat "firstFile.txt")
do
    for j in $(cat "secondFile.txt")
    do
        if [ "$i" = "$j" ]; then
            echo $i[$2] # use first file second column
        fi
    done
done

and I compare strings and if they are the same i want to echo $i[$2] print firstFile.txt second column. Is it possible to do that?

1 Answer 1

1

This can be done easily with awk:

awk 'NR==FNR { a[$1] = $2; next; } { if ($1 in a) { print $1, a[$1]; } }' firstFile.txt secondFile.txt

this will print matched values and second column from first file.
Or you can try this:

#!/bin/bash

while IFS=' ' read -r -a arr; do
    while read j; do
        if [ "${arr[0]}" = "$j" ]; then
            echo "${arr[0]} ${arr[1]}"
        fi
    done < secondFile.txt
done < firstFile.txt

which assumes first and second columns in firstFile.txt are separated by space and that secondFile.txt has one column.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.