如何向以下 git + sed 函数添加完全匹配标志?

如何向以下 git + sed 函数添加完全匹配标志?

我想创建一个 bash 函数,您可以在其中执行 sed 查找和替换,同时忽略.gitignore.我还希望能够向命令添加任何 git grep 标志。例如,为了精确匹配,我应该能够添加-w.

这是我到目前为止所拥有的:

gs {
  local grep_options=()
  local search_pattern
  local replacement

  while [[ $1 =~ ^- ]]; do
    grep_options+=("$1")
    shift
  done

  search_pattern=$1
  replacement=$2

  git grep -l "${grep_options[@]}" "$search_pattern" | xargs sed -i "s/$search_pattern/$replacement/g"
}

gs pattern replacement将成功进行搜索和替换。但gs -w pattern replacement什么也不会做。

这是为什么?如何解决?

答案1

函数声明中有语法错误。

代替

w { ... }

你需要:

w() { ... }

始终将您的脚本传递给https://shellcheck.net在寻求帮助之前:

$ shellcheck file

In file line 1:
gs {
^-- SC2148 (error): Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.
   ^-- SC1083 (warning): This { is literal. Check expression (missing ;/\n?) or quote it.


In file line 2:
  local grep_options=()
  ^---^ SC2168 (error): 'local' is only valid in functions.


In file line 3:
  local search_pattern
  ^---^ SC2168 (error): 'local' is only valid in functions.


In file line 4:
  local replacement
  ^---^ SC2168 (error): 'local' is only valid in functions.


In file line 15:
}
^-- SC1089 (error): Parsing stopped here. Is this keyword correctly matched up?

For more information:
  https://www.shellcheck.net/wiki/SC2148 -- Tips depend on target shell and y...
  https://www.shellcheck.net/wiki/SC2168 -- 'local' is only valid in functions.
  https://www.shellcheck.net/wiki/SC1083 -- This { is literal. Check expressi...

相关内容