我有一个文件(search.patterns),其中包含要搜索到其他txt文件列表中的模式列表。
搜索模式
home
dog
cat
文件1.txt
home 3
tiger 4
lion 1
文件2.txt
dolphin 6
jaguar 3
dog 1
文件3.txt
donkey 3
cat 4
horse 1
所以我想在文件1中搜索模式文件的第一行,在文件2中搜索第二行,在文件3中搜索第三行
输出:
home 3
dog 1
cat 4
我已经写了一些这样的代码:
for f in *.txt;
do
while IFS= read -r LINE;
do grep -f "$LINE" "$f" > "$f.out"
done < search.patterns
done
但是,输出文件为空
任何帮助,高度赞赏,谢谢
使用bash
:
#!/bin/bash
files=( 'file 1.txt' 'file 2.txt' 'file 3.txt' )
while IFS= read -r pattern; do
grep -e "$pattern" "${files[0]}"
files=( "${files[@]:1}" )
done <search.patterns
测试它:
$ bash script.sh
home 3
dog 1
cat 4
该脚本将相关的文件名保存在files
数组中,然后继续从search.patterns
文件中读取模式。对于每个模式,files
都会查询列表中的第一个文件。然后从files
列表中删除已处理的文件(在列表中产生新的第一个文件名)。
如果模式数量超过其中的文件数量files
,则将出现错误grep
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句