bash - 无限次使用 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
有没有聪明的解决方法?我在网上搜索,但找不到任何东西。谢谢您的帮助!
解决方案
将标志设置为 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
推荐阅读
- c++ - 如何将 .cpp 文件中的数组替换为 .json 文件?
- python - 可以用 python 控制软件 GUI 吗?
- android - Raspberry Pi 4 - 蓝牙问题(org.bluez.Error.Failed)
- c# - 我在复杂的 lambda 查询中使用 Distinct 但不起作用
- html - 背景的剥离效果
- javascript - Sequelize - 通过另一个表包含表
- bash - Bash - 在继续之前检查以确保网站可用,否则休眠并重试
- python - (Python)在列表中的字典中提取值
- delphi - 如何在不抑制所有提示的情况下处理虚假的“H2077 Value assigned to '%s' never used”消息?
- java - 使用 openapi4j 在 jar 中使用 refs 解析 Swagger