在 for 循环中使用来自两个不同文件的输入

在 for 循环中使用来自两个不同文件的输入

我有一个文件列表,我想在数据库表列表中搜索这些文件:

[root@host hs]# head -n 3 tables
rec_playinth120116
rec_playinth120216
rec_playinth120316
[root@host hs]# head -n 3 files
0128184628OV30.wav
0128780332OV30.wav
0128439969OV30.wav

我试图通过创建一个简单的 shell 脚本来简化该过程,该脚本仅查看输入文件并将结果输出到包含每个文件的完整路径的第三个文件。本质上是这样的(sed 将输出清理到一个正常的文件路径中,该路径可以用作另一个进程的输入):

psql -d task_hst -A -P tuples_only=on -c "select f_path, file_name from $TABLES where file_name = ''$FILES''"|sed 's/|/\//g' >> $OUT

当它在 for 循环中运行时,显然不会将每个文件与每个表进行比较。我能够获得所需输出的唯一方法是对每个表进行硬编码并将它们作为单独的命令运行,即:

for x in $FILE
do

psql -d task_hst -A -P tuples_only=on -c "select f_path, file_name from rec_playinth120116 where file_name = '$x'"|sed 's/|/\//g' >> $OUT
psql -d task_hst -A -P tuples_only=on -c "select f_path, file_name from rec_playinth120216 where file_name = '$x'"|sed 's/|/\//g' >> $OUT
psql -d task_hst -A -P tuples_only=on -c "select f_path, file_name from rec_playinth120316 where file_name = '$x'"|sed 's/|/\//g' >> $OUT

这不是最优雅或用户友好的做事方式。

理想情况下,文件名将是运行脚本时传递的输入,如下所示:

while true
do
        read -r f1 <&3 || break
        read -r f2 <&4 || break
        psql -d task_hst -A -P tuples_only=on -c "select f_path, file_name from $f1 where file_name = '$f2'"|sed 's/|/\//g' >> $OUT
done 3<$1 4<$2

但是,当我需要它继续搜索所有指定的表时,找到第一个结果后就会中断。

我知道有一种方法可以用 while 或 Paste 之类的东西来做到这一点,但这超出了我的技能范围。有没有一种简单的方法可以实现这一点?

答案1

@barun是的,就是这样,尽管我不知道“笛卡尔积”是描述它的术语。我对这些信息进行了一些研究并得出了以下结论:

while read line1
do
    while read line2
    do psql -d task_hst -A -P tuples_only=on -c "select f_path, file_name from $line1 where file_name = '$line2'"|sed 's/|/\//g' >> $OUT
    done < $2
done < $1

这似乎确实完成了工作。感谢您的答复!有更好的方法吗?

相关内容