我尝试转换文件名并删除特殊字符和空格。 由于某些原因,如果我声明破折号和斜杠不被替换,我的 SED 正则表达式将不起作用。
输入:
/path/to/file 20-456 (1).jpg
预期输出:/path/to/file_20-456_1.jpg
示例:
echo "/path/to/file 20-456 (1).jpg" | sed -e 's/ /_/g' -e 's/[^0-9a-zA-Z\.\_\-\/]//g'
输出:
/path/to/file_20456_1.jpg
所以破折号不在。 当我尝试这个命令时:
echo "/path/to/file 20-456 (1).jpg" | sed -e 's/ /_/g' -e 's/[^0-9a-zA-Z\.\_\-]//g'
输出:
pathtofile_20-456_1.jpg
破折号在那里,但没有目录斜杠,我无法移动文件。 我想知道为什么如果我将
\/
添加到正则表达式模式中,用破折号替换就不再起作用了。
有什么建议吗?
根据您显示的示例和尝试,请尝试以下
awk
代码。
echo "/path/to/file 20-456 (1).jpg" |
awk 'BEGIN{FS=OFS="/"} {gsub(/ /,"_",$NF);gsub(/-|\(|\)/,"",$NF)} 1'
解释: 简单的解释是,通过
echo
打印值 /path/to/file 20-456 (1).jpg
作为 awk
程序的标准输入。在awk
程序中,将FS
部分中的OFS
和/
设置为BEGIN
。然后在主程序中使用 gsub
在最后一个字段($NF)中用 _
全局替换空格,然后在最后一个字段中用 NULL 全局替换 -
OR (
OR )
然后提及 1
将打印该行。
您可以使用 Bash 中的字符串操作来获得结果:
#!/bin/bash
path="/path/to/file 20-456 (1).jpg"
fldr="${path%/*}" # Get the folder
file="${path##*/}" # Get the file name
file="${file// /_}" # Replace spaces with underscores in filename
echo "$fldr/${file//[^[:alnum:]._-]/}" # Get the result
查看在线演示,产生
/path/to/file_20-456_1.jpg
。
快速注释:
${path%/*}
- 从 /
的末尾删除直到
path
${path##*/}
- 删除从 path
开始到最后 /
(包括它)${file// /_}
将 _
中的所有空格替换为
file
${file//[^[:alnum:]._-]/}
从 .
中删除所有非字母数字、_
、-
和 file
的字符。