首页 > 解决方案 > 无限次使用 bash 参数?

问题描述

我在下面有一个 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 

有没有聪明的解决方法?我在网上搜索,但找不到任何东西。谢谢您的帮助!

标签: bashargumentscommand-line-arguments

解决方案


将标志设置为 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 

推荐阅读