终端 SED 正则表达式因破折号和斜杠而失败

问题描述 投票:0回答:2

我尝试转换文件名并删除特殊字符和空格。 由于某些原因,如果我声明破折号和斜杠不被替换,我的 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

破折号在那里,但没有目录斜杠,我无法移动文件。 我想知道为什么如果我将

\/
添加到正则表达式模式中,用破折号替换就不再起作用了。

有什么建议吗?

linux bash sed terminal
2个回答
1
投票

根据您显示的示例和尝试,请尝试以下

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
将打印该行。


0
投票

您可以使用 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
    的字符。
© www.soinside.com 2019 - 2024. All rights reserved.