【问题标题】:bash_profile function to git grep and replacebash_profile 函数到 git grep 和替换
【发布时间】:2020-06-11 03:47:39
【问题描述】:

我想在我的 ~/.bash_profile 中创建一个函数,它会 git grep 并列出包含字符串的文件,然后用另一个字符串替换所有出现的字符串

function git-replace() { eval git grep -l ${1} | xargs sed -i '' -e 's/${1}/${2}/g' ; }

但是,如果我运行函数 git-replace "Type1" "Type2" ,则什么也不会发生。我在这里做错了什么?

【问题讨论】:

  • 给新手的建议:如果一个答案解决了您的问题,请点击旁边的大复选标记 (✓) 接受它,也可以选择投票(投票至少需要 15 个声望)点)。如果您发现其他答案有帮助,请给他们投票。接受和投票有助于未来的读者。请看the relevant help-center article

标签: bash git xargs


【解决方案1】:

有两个问题:

  • 不要使用邪恶 eval
  • 如果你想扩展一个变量,不要使用单引号,而是使用双引号,所以:
git-replace() {
    git grep -l "$1" | xargs sed -i '' -e "s/$1/$2/g"
}

并且不需要现代 shell 中的 function 语句。

了解如何在 shell 中正确引用,这非常重要:

“双引号”包含空格/元字符和每个扩展的每个文字:"$var""$(command "$var")""${array[@]}""a & b"。将'single quotes' 用于代码或文字$'s: 'Costs $5 US'ssh host 'echo "$HOSTNAME"'。见
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 2011-11-21
    • 2018-08-21
    • 1970-01-01
    • 2012-09-09
    • 2016-01-29
    相关资源
    最近更新 更多