gpt4 book ai didi

regex - bash 正则表达式 : Grep for tilde '~' and hyphen '-' on array loop

转载 作者:行者123 更新时间:2023-11-29 09:32:47 25 4
gpt4 key购买 nike

我正在尝试创建一个 expect_commands bash 函数来检查文件中是否存在正则表达式:

function expect_commands 
{
args_array=()
for (( i = 2; i <= $#; i++ )); do
args_array[i]=${!i}
if grep -Fxqe "${args_array[$i]}" "$hist_file" || grep -Fxqe "${args_array[$i]}/" "$hist_file" || grep -Fxqe "${args_array[$i]} " "$hist_file" || grep -FxqE "${args_array[$i]}" "$hist_file"
then
response "$1" $COUNT
else
tell_error "$1" $COUNT
fi
done
}

使用以下参数调用该函数:

expect_commands "remove entire ~/workspace/test-website/css directory" "rm -r test-website/css" "rm -r test-website/css/" "rm -Rf ~/workspace/test-website/css" "rm -rf ~/workspace/test-website/css" "rm -R ~/workspace/test-website/css"

其中参数 $1 是任务。从 $2 到结尾的参数是用户可能输入到终端的每个可能组合。

这些输入被保存到 ~/.bash_history 文件中,并从那里使用 grep 进行评估:

if grep -Fxqe "${args_array[$i]}" "$hist_file" || grep -Fxqe "${args_array[$i]}/" "$hist_file" || grep -Fxqe "${args_array[$i]} " "$hist_file" || grep -FxqE "${args_array[$i]}" "$hist_file"

该函数传递如下输入:

rm -r 测试网站/cssrm -r 测试网站/css/

但是说到:

rm -Rf ~/workspace/test-website/cssrm -rf ~/workspace/test-website/cssrm -R ~/workspace/test-website/css

grep 无法匹配这些行。

我有时会遇到的一些错误是:

添加 -FxqE 选项时:grep:指定了冲突的匹配器

有什么想法吗?

最佳答案

你的函数可以被简化:为什么你需要一个数组来保存参数?

function expect_commands {
local label=$1
shift
for arg do
arg=$( sed "s/ ~/ $HOME/g" <<< "$arg" ) # translate ~ to $HOME
if grep -Fxq -e "$arg" -e "$arg/" -e "$arg " "$HISTFILE"
then
response "$label" $COUNT
else
tell_error "$label" $COUNT
fi
done
}

什么是$COUNT?避免使用全局变量。

关于regex - bash 正则表达式 : Grep for tilde '~' and hyphen '-' on array loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com