我正在这里阅读指南http://mywiki.wooledge.org/BashFAQ/030 http://mywiki.wooledge.org/BashFAQ/030在这个链接上给出了一些例子我试图理解它们一个示例代码说
# Bash
# Replace all spaces with underscores
for f in *\ *; do mv -- "$f" "${f// /_}"; done
到目前为止我所知道的是在搜索和替换时使用反斜杠来表示特殊字符,例如 ~ 或 # 等的空格
示例或在上面示例中的 shell 脚本中,它们有
used ${f// /_}
正斜杠,我不清楚这是否允许?
在同一页面的另一个示例中
他们给出了一个删除空格并将其替换为下划线的示例
find . -depth -name "* *" -exec bash -c 'dir=${1%/*} base=${1##*/};
mv "$1" "$dir/${base// /_}"' _ {} \;
在上面的例子中我不清楚以下内容
1) dir=${1%/*}
2) base=${1##*/}
3)当它说mv "$1"
上述语句中的 $1 是什么意思,
4)最后find命令被关闭-exec <something> _ {} \;
现在下划线 _ 、大括号 {} 和反斜杠后跟 \; 上面的冒号有什么用?
在第三个例子中他们说
# tolower - convert file names to lower case
# POSIX
for file in "$@"do
[ -f "$file" ] || continue # ignore non-existing names
newname=$(echo "$file" | tr '[:upper:]' '[:lower:]') # lower case
[ "$file" = "$newname" ] && continue # nothing to do
[ -f "$newname" ] && continue # don't overwrite existing files
mv -- "$file" "$newname"done
我不清楚以下几行
5) [ -f "$file" ] || continue # ignore non-existing names
我不清楚用 [ ] 测试条件如果 $file 存在那么 OR 条件有什么用 ||这里和 continue 语句
6) [ -f "$newname" ] && continue # don't overwrite existing files
这里与第5点有同样的疑问
${f// /_}
意思是:用下划线替换所有出现的空格
ref http://thegeekstuff.com/2010/07/bash-string-manipulation
${1%/*}
意思是:删除最短匹配/*
从字符串末尾开始
ref http://thegeekstuff.com/2010/07/bash-string-manipulation
${1##*/}
意思是:删除最长的匹配*/
从字符串前面
ref http://thegeekstuff.com/2010/07/bash-string-manipulation
当它说mv "$1"
1美元是什么意思
$1
是第一个位置参数。所以如果你的脚本有这个
echo $1
你这样称呼
foo.sh 111
那么输出将是
111
最后 find 命令被关闭-exec <something> _ {} \;
现在下划线有什么用_
, 大括号{}
和一个反斜杠
接下来是上面的冒号\;
?
下划线是参数的占位符$0
ref http://linux.die.net/man/1/bash
The {} \;
习语与find
,也就是说:为每个文件运行一次此命令
ref http://linux.die.net/man/1/find
[ -f "$file" ] || continue
意思是:如果$file
不是文件,则继续(立即结束循环的当前迭代并开始下一个)
ref http://ss64.com/bash/test.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)