简体   繁体   English

Bash变量在OSX终端中返回“未找到命令”

[英]Bash variable returns “command not found” in OSX Terminal

I tried using some variables to rename a few files, but it failed miserably. 我尝试使用一些变量重命名一些文件,但它失败了。 I've tried different ways of getting it to work, but to no avail. 我已经尝试了不同的方式让它工作,但无济于事。 As far as I understand the documentation, this is the correct way of doing things - however now I'm stumped... 据我了解文档,这是正确的做事方式 - 但是现在我很难过......

Here's the code (as written in the file rename_prefix.sh ): 这是代码(如文件rename_prefix.sh ):

 #!/bin/sh
 NEWPREF="LALA"
 OLDPREF="LULU"
 for f in $OLDPREF*; do mv $f $(echo $f | sed 's/^$OLDPREF/$NEWPREF/g'); done

Here's the error message: 这是错误消息:

 usage: mv [-f | -i | -n] [-v] source target
   mv [-f | -i | -n] [-v] source ... directory

Initially I thought the problem lay in using variables with what I assume are the regular expressions, but as can be seen from the error messages, the problem lies where the variables are first declared. 最初我认为问题在于使用我认为是正则表达式的变量,但从错误消息中可以看出,问题在于首先声明变量的地方。

What's going on here? 这里发生了什么?

This can be done entirely in the shell, which also avoids the possible problem of escaping metacharacters for the sed substitution patterns. 这可以完全在shell中完成,这也避免了为sed替换模式转义元字符的可能问题。 It is also blazingly fast because it saves two forks per file renamed. 它也非常快,因为它为每个重命名的文件节省了两个叉子。

NEWPREF="LALA"
OLDPREF="LULU"
for f in "$OLDPREF"*; do
   mv "$f" "$NEWPREF${f#$OLDPREF}"
done

If you want to learn more about removing suffixes and prefixes from shell variable values, read up the POSIX spec on parameter expansion (which all of zsh, ksh, mksh, and bash support). 如果您想了解有关从shell变量值中删除后缀和前缀的更多信息,请阅读有关参数扩展POSIX规范 (所有zsh,ksh,mksh和bash都支持)。

PS: The only way you can get an error like rename_prefix.sh: line 2: NEWPREF: command not found is if you had whitespace after NEWPREF and before the = . PS:你可以获得像rename_prefix.sh: line 2: NEWPREF: command not found这样的错误的唯一方法rename_prefix.sh: line 2: NEWPREF: command not found如果你在NEWPREF之后和=之前有空格。 It looks very much like your program as posted is not exactly the program you ran. 它看起来非常像您发布的程序并不完全是您运行的程序。 Did you type it instead of cut'n'paste it? 你输入它而不是cut'n'paste吗?

Alright so assuming you don't require POSIX, and guessing about certain other details, here's the same thing with general corrections applied. 好吧,假设您不需要POSIX,并猜测某些其他细节,这里应用了一般修正的相同内容。

#!/bin/bash
newpref=LALA
oldpref=LULU

shopt -s nullglob

for f in "$oldperf"*; do
    mv -- "$f" "${f/#"$oldpref"/$newpref}"
done

or POSIX 或POSIX

#!/bin/sh
newpref=LALA
oldpref=LULU

for f in "$oldpref"*; do
    [ -e "$f" ] || break
    mv -- "$f" "${newpref}${f#"$oldpref"}"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM