【问题标题】:Use a bash argument unlimited times?无限次使用 bash 参数?
【发布时间】:2019-09-03 17:25:50
【问题描述】:

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

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

【问题讨论】:

  • 您的 txt 文件数量是否有限?您可能想grep所有txt文件并按目录和搜索项分组报告结果,因此用户只需要输入输出文件。

标签: bash arguments command-line-arguments


【解决方案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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多