【问题标题】:Directory names - Stripping white space and other formatting目录名称 - 去除空格和其他格式
【发布时间】:2014-12-08 20:00:03
【问题描述】:

我是 bash 新手,正在学习 sedawk 以及该平台提供的更多工具。在我的 linux 机器中,我有一个包含子目录的音乐目录。这些子目录的名称大写。我正在尝试使该音乐目录中的所有文件夹小写并去掉空格。除了在子目录名称中删除空格之外,不更改最后一个连字符之后的任何内容。一个文件可能有很多连字符。我只考虑最后一个。我怎么能这样做?

while read -r file; do
    new_file=$(echo "$file" | sed -re 's/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/' -e 's/ /_/g' -e 's/_-/-/g')
        if [ "$file" != "$new_file" ]; then
                mv "$file" "$new_file"
        fi
done

例如:

输入

New- Survivor - Eye Of The Tiger – 12wOlL

想要的结果:

new-survivor_-_ eye_of_the_tiger-12wOlL

当前结果:

new-Survivor_-_ Eye_of_The_Tiger-12wOlL

【问题讨论】:

  • 您需要再澄清一下转换规则。为什么New- Survivor 变成了new-survivorSurvivor - Eye 变成了survivor_-_ eye 又一次Tiger – 12wOlL 变成了tiger-12wOlL- 之后的空格何时应转换为_,何时应剥离?
  • @anubhava 我正在附加New- 其他所有内容都是原始文件名。这就是为什么其他连字符被下划线包围的原因。例外是第一个和最后一个连字符

标签: linux bash unix ubuntu sed


【解决方案1】:

如下更改你的 sed 命令,

$ echo 'New- Survivor - Eye Of The Tiger – 12wOlL' | sed -re 's/^([^-]*-)\s*([^–]*)\s*–/\L\1\L\2–/;s/ /_/g;s/_-_/_-_ /g;s/_–_/-/g'
new-survivor_-_ eye_of_the_tiger-12wOlL

【讨论】:

    【解决方案2】:

    你可以使用这个sed命令:

    s='New- Survivor - Eye Of The Tiger - 12wOlL'
    echo "$s" | sed 's/^\(.*\)\(-[^-]*\)$/\L\1\E\2/; s/ *- */-/; s/^\(.*\) \+- *\([^-]*\)$/\1-\2/; s/ /_/g'
    new-survivor_-_eye_of_the_tiger-12wOlL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 2018-12-20
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多