mac 批处理改名
比如要把所有 .htm 改为 .html
for i in *.htm;do mv "$i" "${i/.*/.html}";done
注意:引号是为了处理 带空格的文件名。我一般用下面命令先测试:
for in in *.htm;echo ${i/.*/.html};done
${} 语法(Parameter Expansion)
语法:
${parameter/pattern/string} 或者 ${parameter//pattern/string}
- 第一个匹配第一次(/);
- 二匹配每次。(//)
- pattern中 # 表示开始
- pattern中% 表示结尾
- pattern中 空字符串不处理
- @ or * (没看懂)
The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pat- tern against its value is replaced with string. In the first form, only the first match is replaced. The second form causes all matches of pattern to be replaced with string. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is @ or , the substitution operation is applied to each positional parameter in turn, and the expan- sion is the resultant list. If parameter is an array variable subscripted with @ or , the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
更多例子
比如要把
- image0001.png
- image0002.png
- …
改为
- 0001.png
- 0003.png
- …
用 for f in *.png; do mv "$f" "${f#image}"; done
用 sed
ls | sed -n 's/\(.*\)\(\.htm\)/mv "\1\2" "\1.html"/p'|sh
特别注意:ls 必须是默认的 纯文件名输出,而不是 alias 以后的 alias ls=”ls -lh” 之类! 最好先用 echo 先查看
或者包括当前子目录都转
find . -type f | sed -n 's/\(.*\)\(\.htm\)/mv "\1\2" "\1.html"/p'|sh
解释:
这种正则比较难读。太严格,其实主要就是括号 () 必须转义 ()
sed -n ‘s/AAA/BBB/p’
s (Substitute)替换;把 AAA 换成 BBB;最后的 p 表示 print。疯狂的 sed !
文件名全部改小写
for f in *; do mv "$f" "
echo $f | tr “[:upper:]” “[:lower:]”"; done
延伸
a=aaabcd echo $a | tr 'a' 'k'
返回 kkkbcd
echo "abcabc" | sed 's/a/x/g'
返回 xbcxbc