【问题标题】:Bash regex: Grep for tilde '~' and hyphen '-' on array loopBash 正则表达式:Grep 用于数组循环上的波浪号“~”和连字符“-”
【发布时间】:2015-11-01 03:57:47
【问题描述】:

我正在尝试创建一个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 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

grep 无法匹配这些行。

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

添加 -FxqE 选项时: grep: conflicting matchers specified

有什么想法吗?

【问题讨论】:

  • 改用绝对路径怎么样?
  • “grep:指定的匹配器冲突”是因为您不能在同一个 grep 命令中使用 -F 和 -E。
  • 你能把你的历史文件放在一个要点中并分享它(或者至少有足够的内容可以玩。我运行它时没有收到错误(删除 -F -E 冲突后)论点),但我想针对真实数据进行测试
  • 更好的是,使用set -x 运行脚本并获取输出。
  • @Albert 这是因为试图解决此挑战的人可能会编写主~ 路径以删除文件夹或文件。绝对路径确实有效。

标签: regex bash grep


【解决方案1】:

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

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 是什么?避免使用全局变量。

【讨论】:

  • 感谢您的回复。我需要数组的原因是因为要求用户完成一个任务,在这种情况下:remove整个~/workspace/test-website/css目录,他/她可能会输入几个@ 987654323@ 组合(绝对/相对路径)和命令选项。该数组包含可能答案的列表。
猜你喜欢
  • 2012-06-22
  • 1970-01-01
  • 2010-10-30
  • 2019-08-16
  • 2019-12-28
  • 2018-01-26
  • 2018-04-16
  • 1970-01-01
相关资源
最近更新 更多