如何在zsh中查找和替换字符串中的特殊字符

时间:2014-08-22 05:35:36

标签: replace zsh

我正在尝试构建secure copy protocol快速功能。当我运行命令时,它将使用单个文件或整个目录,但只要我在/*后面local_repo返回zsh: no matches found: hackingedu/*

如果我输入命令scp hackingedu\/\* hackingedu,则命令正常工作。我想我已走上正轨,但无法让它发挥作用。

contains() {
    string="$1"
    substring="$2"
    if test "${string#*$substring}" != "$string"
    then
        # echo '$substring is in $string'
        return 1    # $substring is in $string
    else
        # echo '$substring is not in $string'
        return 0    # $substring is not in $string
    fi
}


# Quickly scp files in Workspace to Remote
function scp() {
    local_repo="$1"
    remote_repo="$2"

    # find all the `*` and replace with `/*`
    if [ contains $local_repo '*' ]; then
        # replace all instances of * with \*                 <- HOW TO DO
    fi
    command scp -r $LOCAL_REPOS/$local_repo $ALEX_SERVER_UNAME@$ALEX_SERVER_PORT:$ALEX_REMOTE_ROOT_PATH/$remote_repo

    # Description: $1: Local Repo  |  $2:  Remote Repo
    # Define ex: scpp local/path/to/file/or/directory/* remote/path/to/file/or/directory/*
    # Live ex: scpp alexcory/index.php alexcory/index.php
    # Live ex: scpp alexcory/* alexcory/*
    #
    # This Saves you from having long commands that look like this:
    # scp -r ~/Google\ Drive/server/Dev/git\ repositories/hackingedu/* alexander@alexander.com:/home2/alexander/public_html/hackingedu/beta
}

尝试执行的命令:scp -r ~/Google\ Drive/server/Dev/git\ repositories/hackingedu/* alexander@alexander.com:/home2/alexander/public_html/hackingedu/beta

有关如何查找和替换*的任何想法?如果有更好的方法,请告诉我们! :)

如果您知道如何在bash中执行此操作,我也希望您提供意见!

参考文献:

1 个答案:

答案 0 :(得分:0)

您可以使用noglob为您的scp调用添加前缀(这将为该命令关闭通配,例如noglob ls *)或使用

autoload -U url-quote-magic
zle -N self-insert url-quote-magic
zstyle -e :urlglobber url-other-schema '[[ $words[1] == scp ]] && reply=("*") || reply=(http https ftp)'

以上内容应在您使用*时生成zsh自动引用scp

[...]

无论如何,你应该知道你可以使用${(q)variable_name}轻松引用特殊字符,例如

% foo='*&$%normal_chars'
% echo $foo
*&$%normal_chars
% echo ${(q)foo}
\*\&\$%normal_chars