Zsh:是否可以使用变量的值作为替换模式?

col*_*inh 5 zsh shell-script

是否可以执行以下操作?

g=$f:s/$in/$out/;

或者

g=$g:s/$in[$i]/$out[$i]/;

我尝试过随机字符组合,例如${~in}g=$g:ps/,但是,正如你所看到的,我不是 zsh 专家——猜测对我没有任何帮助:-)我什至尝试阅读手册页...

编辑:我正在尝试编写自己的 zmv 类型命令:

# in   a*b* -> a b NULL     rn a*b* *c*d   aXXbYY  -->  XXcYYd
# out  *c*d -> NULL c d     rn inv* mag*   inv.ext inv.spc -->  mag.ext mag.spc

alias rn='noglob frn'

function frn() {                                                                                                   
    local in out m n f g i
    setopt localoptions glob histsubstpattern

    in=("${(@s:*:)1}")                          # split $1 and $2 on '*'
    out=("${(@s:*:)2}")                         # keeping NULL fields

    m=${#in[@]}                                 # count n(array-elements)
    n=${#out[@]}

    if [[ $m = $n ]] {
        foreach f ($~1)                         # foreach file in globbed $1
            g=$f
            for (( i = 1; i < n; i += 1 )); do
                g=$g:s/$in[$i]/$out[$i]/        # subst corresponding fields
            done

            g=$g:s/%$in[$i]/$out[$i]/           # last subst has % anchor

            print '$f --> $g'
            mv $f $g
        end
    } else {
        print "n(*) must be same for both patterns"
    }
}
Run Code Online (Sandbox Code Playgroud)

don*_*sti 4

$out与展开的不同,$in这里被视为文字字符串......所以什么也没有发生(除非字面f包含$in)。
要在左侧展开,您需要HIST_SUBST_PATTERN设置

s/l/r[/]

如下所述r替代。 ...... 默认情况下,替换的左侧不是模式,而是字符串[...] ......如果 设置了 该选项,则为被视为文件名生成中描述的通常形式的模式。l



HIST_SUBST_PATTERNl

所以

setopt histsubstpattern
Run Code Online (Sandbox Code Playgroud)

然后它应该可以工作......