我下面有一个Grep函数:
#!/bin/bash
echo What directory contains the text files with your data?
read mydirectory
cd $mydirectory
echo What should we name your output?
read $myoutput
for file in *.txt; do
grep -q $3 "$file" && grep -q foo "$file" && echo ""$file"">>"$myoutput.txt"
done
我真的很希望能够使用命令行中的参数来更快地运行脚本。我希望能够按向上箭头并更改一些参数,然后再次运行脚本。
$ 1变量将始终是我要在其上运行Grep的.txt文件的目录。 $ 2变量将始终是我要命名输出文件的名称。此后,每个参数都需要在grep函数的$ 3位置使用。我的问题是,我需要能够满足“ n”组条件,具体取决于我在文件中查找的内容。
例如有时可能是:
#!/bin/bash
echo What directory contains the text files with your data?
read mydirectory
cd $mydirectory
echo What should we name your output/
read $myoutput
for file in *.txt; do
grep -q 30 "$file" && grep -q 8 "$file" && grep -q 12 "$file" && grep -q B "$file" && echo ""$file"">>"$myoutput.txt"
done
其他时候可能是:
#!/bin/bash
echo What directory contains the text files with your data?
read mydirectory
cd $mydirectory
echo What should we name your output?
read $myoutput
for file in *.txt; do
grep -q 30 "$file" && grep -q 8 "$file" && grep -q 12 "$file" && grep -q 13 "$file" && grep -q 18 "$file" && grep -q B "$file" && echo ""$file"">>"$myoutput.txt"
done
为此有灵巧的解决方法吗?我在网上搜索,但找不到任何内容。谢谢您的帮助!
答案 0 :(得分:1)
将标志设置为true并遍历所有搜索词。如果搜索失败,请清除该标志。
for file in *.txt; do
match=1
for term in "${@:3}"; do
grep -q "$term" "$file" || { match=0; break; }
done
((match)) && echo "$file">>"$myoutput.txt"
done
这是一个辅助功能的好地方。
all_found() {
local file=$1
shift
local term
for term in "$@"; do
grep -q "$term" "$file" || return 1
done
return 0
}
for file in *.txt; do
all_found "$file" "${@:3}" && echo "$file">>"$myoutput.txt"
done