最初/2番目のファイル列のインポート

最初/2番目のファイル列のインポート

これには2つのforループがあります。

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

文字列を比較して同じ場合は、2番目の列をecho $i[$2] 印刷したいと思います。firstFile.txtこれは可能ですか?

ベストアンサー1

これは次の方法で簡単に実行できますawk

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

これにより、最初のファイルと2番目の列に一致する値が印刷されます。
または、次のことを試すことができます。

#!/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

firstFile.txtの最初の列と2番目の列がスペースで区切られ、secondFile.txtに1つの列があるとします。

おすすめ記事