使用 bash 我需要删除文件名中文件扩展名之前的尾随空格

2023-12-06

我有数百个文件,它们看起来类似于:

"QDN34 Unit5 mark-up - Judy .pdf"  
"QDN34 Unit7 mark-up - Judy .pdf"  
"file with two character ext .ai"  
"file with dot. trailing space and no ext "  
"file with no ext"

请注意,除了最后一个之外,所有文件的末尾都有一个空格,不包括相关的文件扩展名。

我需要保留文件名中的空格(不理想)并删除那些尾随空格。
The result应该:

"QDN34 Unit5 mark-up - Judy.pdf"
"QDN34 Unit7 mark-up - Judy.pdf"  
"file with two character ext.ai"  
"file with dot. trailing space and no ext"  
"file with no ext"

到目前为止我有:

newName=$(find . -type f -name \*\ .* | cut -d'.' -f2 | sed 's/\ $//' | sed 's/^\/*//')
extens=$(find . -type f -name \*\ .* | sed 's@.*/.*\.@.@')
oldName=$(find . -type f -iname \*\ .* | sed 's/^\.\/*//')
for f in "$oldName" ; do mv -nv "$oldName" "$newName""$extens" ; done

但我收到的错误看起来索引不匹配。感觉我应该使用数组,但我不知道如何使用。

输出是:

mv: rename file with two character ext .ai  
QDN34 Unit5 mark-up - Judy .pdf  
QDN34 Unit7 mark-up - Judy .pdf to file with two character ext  
QDN34 Unit5 mark-up - Judy  
QDN34 Unit7 mark-up - Judy.ai  
.pdf  
.pdf: No such file or directory

Bash 解决方案

这也是 Bash 解决方案可能有用的地方。以下测试扩展(max 4 chars + .)设置为extsz在脚本中。如果找到扩展名,脚本会删除文件名中的空格,然后将文件从旧名称移动到新名称(实际移动在下面注释)。它依赖于参数扩展/子串替换操作空格和文件名:

#!/bin/bash

declare -i extsz=-5     # extension w/i last 4 chars

## trim leading/trailing whitespace
function trimws {
    [ -z "$1" ] && return 1
    local strln="${#1}"
    [ "$strln" -lt 2 ] && return 1
    local trimstr=$1
    trimstr="${trimstr#"${trimstr%%[![:space:]]*}"}"  # remove leading whitespace characters
    trimstr="${trimstr%"${trimstr##*[![:space:]]}"}"  # remove trailing whitespace characters
    printf "%s" "$trimstr"
    return 0
}

## for each filename read from stdin
while read -r ffname || test -n "$ffname" ; do

    ## test for extension and set 'ext' if present
    for ((i=$extsz; i<0; i++)); do
        [ "${ffname:(i):1}" == '.' ] && { ext=${ffname:(i)}; break; }
    done

    ## if extension, move the file to name w/o trailing space w/orig extension
    if [ -n "$ext" ]; then

        fname="${ffname%.*}"          # separate filename from extension
        fnwosp="$(trimws "$fname")"   # trim whitespace from filename

        printf "   renaming :  '%s' -> '%s'\n" "$ffname" "${fnwosp}${ext}"
        #mv "$ffname" "${fnwosp}${ext}"  # commented for testing

    else
        ## if no extension, just trim whitespace and move
        printf "   renaming :  '%s' -> '%s'\n" "$ffname" "$(trimws "$ffname")"
        # mv "$ffname" "$(trimws "$ffname")"
    fi

    unset ext       # unset 'ext' for next iteration

done

exit 0

Input

$ cat dat/wfname.txt
QDN34 Unit5 mark-up - Judy .pdf
QDN34 Unit7 mark-up - Judy .pdf
file with two character ext .ai
file with dot. trailing space and no ext
file with no ext

Output

$ bash fixfilenames.sh <dat/wfname.txt
   renaming :  'QDN34 Unit5 mark-up - Judy .pdf' -> 'QDN34 Unit5 mark-up - Judy.pdf'
   renaming :  'QDN34 Unit7 mark-up - Judy .pdf' -> 'QDN34 Unit7 mark-up - Judy.pdf'
   renaming :  'file with two character ext .ai' -> 'file with two character ext.ai'
   renaming :  'file with dot. trailing space and no ext' -> 'file with dot. trailing space and no ext'
   renaming :  'file with no ext' -> 'file with no ext'

Note:当读自stdin,shell 将去除不带扩展名的文件名的尾随空格。

读取文件名作为参数

为了说明如何从不带扩展名的文件名末尾删除空格,有必要引用并读取文件名作为参数。如果这就是您所需要的,这里有一个替代品。无论如何,将文件名作为参数读取而不是从标准输入中批量读取可能更有意义:

#!/bin/bash

declare -i extsz=-5     # extension w/i last 4 chars

## trim leading/trailing whitespace
function trimws {
    [ -z "$1" ] && return 1
    local strln="${#1}"
    [ "$strln" -lt 2 ] && return 1
    local trimstr=$1
    trimstr="${trimstr#"${trimstr%%[![:space:]]*}"}"  # remove leading whitespace characters
    trimstr="${trimstr%"${trimstr##*[![:space:]]}"}"  # remove trailing whitespace characters
    printf "%s" "$trimstr"
    return 0
}

## test at least 1 command line argument
[ $# -gt 0 ] || {
    printf "error: insufficient input.  usage: %s <filename>\n" "${0##*/}"
    exit 1
}

## for each of the filenames give as arguments
for ffname in "$@"; do

    ## test for extension and set 'ext' if present
    for ((i=$extsz; i<0; i++)); do
        [ "${ffname:(i):1}" == '.' ] && { ext=${ffname:(i)}; break; }
    done

    ## if extension, move the file to name w/o trailing space w/orig extension
    if [ -n "$ext" ]; then

        fname="${ffname%.*}"          # separate filename from extension
        fnwosp="$(trimws "$fname")"   # trim whitespace from filename

        printf "   renaming :  '%s' -> '%s'\n" "$ffname" "${fnwosp}${ext}"
        #mv "$ffname" "${fnwosp}${ext}"  # commented for testing

    else

        ## if no extension, just trim whitespace and move
        printf "   renaming :  '%s' -> '%s'\n" "$ffname" "$(trimws "$ffname")"
        # mv "$ffname" "$(trimws "$ffname")"

    fi

    unset ext

done

exit 0

Example

$ bash fixfilenames.sh 'testfile w end space '
   renaming :  'testfile w end space ' -> 'testfile w end space'

$ bash fixfilenames.sh 'file with two character ext .ai'
   renaming :  'file with two character ext .ai' -> 'file with two character ext.ai'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 bash 我需要删除文件名中文件扩展名之前的尾随空格 的相关文章

随机推荐

  • 为什么当我设置元素位置:绝对时线性渐变消失?

    我制作了一个渐变背景 我想将这个文本块居中 我的目标是创建一个位于屏幕中间中心的标题 无论视口的分辨率如何 所以我把这个 header 设置为绝对位置 并使用了我在网上找到的这种集中方法 它完美地集中 问题是 渐变背景变成白色 看起来标题位
  • 查找开放会话数

    我正在寻找一种简单 无数据库 的方法来列出网站上有多少活跃用户 我能想到的最简单的方法是计算打开会话的数量 这段代码应该管用 number of users count scandir ini get session save path 当
  • std regex_search 仅匹配当前行

    我使用各种正则表达式逐行解析 C 源文件 首先我读取字符串中文件的所有内容 ifstream file stream commented cpp ifstream binary std string txt std istreambuf i
  • 如何将参数注入 TestCafé 测试?

    设想 我使用 API 运行用代码封装的 TestCaf 我有一个想要参数化的测试 使用不同的动态值进行测试 Problem Testcaf 不支持向测试发送参数 有没有办法注入值 您可以使用进程 env将参数从运行程序脚本传递给 TestC
  • 如何从 Guava MultiMap 中获取每个条目及其关联的相应值?

    我正在读取一个巨大的 csv 文件 其中包含重复的条目 我能够将整个 csv 文件读入Multimap 我还能够获取具有重复值的键集并将它们写入文件 我想获取与每个键关联的值并将其写入文件 但无法这样做 我似乎找不到任何可能对我有帮助的选项
  • 如何在 Rails 4 中将 PDF 转换为 Excel 或 CSV

    我已经搜索了很多 除非在这里问这个问题 否则我别无选择 你们知道有一个在线转换器有 API 或 Gem s 可以将 PDF 转换为 Excel 或 CSV 文件吗 我也不确定这里是否是问这个问题的最佳地点 我的应用程序是在 Rails 4
  • 有没有办法使用命令行 cURL 跟踪重定向?

    我知道在 php 脚本中 curl setopt ch CURLOPT FOLLOWLOCATION true 将遵循重定向 有没有办法使用命令行 cURL 跟踪重定向 使用位置标头标志 curl L
  • 为什么 re.sub('.*?', '-', 'abc') 返回 '-a-b-c-' 而不是 '--------'?

    这是python2 7的结果 gt gt gt re sub abc a b c 我以为的结果should如下 gt gt gt re sub abc 但事实并非如此 为什么 据我所知 对这种行为的最好解释来自regexPyPI 包 其目的
  • JSON.Stringify 在 Scripting.Dictionary 对象上失败

    我正在开发一个 ASP 经典项目 在该项目中我实现了 JScript JSON 类here 它能够与 VBScript 和 JScript 互操作 并且几乎与以下位置提供的代码完全相同 json org 我的团队经理要求我在这个项目中使用
  • 如何交错两个数组列表?

    我正在尝试开发一个程序 通过将一副牌分成两部分然后将它们交错来洗牌 班级甲板代表一副 52 张牌 有两种方法 牌组 int n and 抽卡卡 牌组 int n 是构造函数 该参数告诉我们应该洗牌多少轮 在每轮洗牌中 整副牌首先被分成两个子
  • 用于 dotnet 的 Google API v3;使用带有 API 密钥的日历

    我正在尝试使用 v3 API http code google com p google api dotnet client 读取我自己的 Google 日历 我最终想要的是通过自定义控件在我的网站上显示来自 Google 日历的我自己的日
  • 是否可以删除 .NET 中未使用的代码/程序集?

    我的应用程序中有一个控件库 对于我正在开发的应用程序类型来说有点大 该库超过 2Mb 我几乎不使用它的功能 我想说我使用了它所有功能的 5 到 10 有没有办法从库中删除我的应用程序从不使用的代码 P S 该库不是我开发的 也不是开源的 不
  • 如何在Linux中创建给定大小的文件?

    出于测试目的 我必须生成一定大小的文件 以测试上传限制 在 Linux 上创建特定大小的文件的命令是什么 对于小文件 dd if dev zero of upload test bs file size count 1 Where file
  • Kotlin 中 KProperty1 的通用扩展

    我有以下代码 import kotlin reflect KProperty1 infix fun
  • Webpack 文件加载器输出 [对象模块]

    我正在使用 webpackHtmlWebpackPlugin html loader and file loader 我有一个简单的项目结构 其中不使用任何框架 而仅使用打字稿 因此 我直接将 HTML 代码写入index html 我还使
  • XAML 中的 WPF 文本块绑定

    我正在更新一些现有的 WPF 代码 我的应用程序有许多定义如下的文本块
  • 用于复杂 ID 的 CSS 通配符

    如果我有一个 css 选择器 例如 subtab 1 subtab 2 etc 我可以这样制作通配符选择器div id subtab 但我不知道如何为选择器制作通配符 例如 subtab 1 sub1 subtab 1 sub2 subta
  • 如何在 Silverlight 3(或 4)中从 URL 播放 MP4(H.264 视频)? [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 所以我有一些网址MP4文件 我想开发一个简单的Silverlight应用程序来玩它 怎么做 最好有示例代码 Ole Jak 以下是建议的分步步骤 步骤 1 使用 Visual S
  • 在 Ubuntu 上使用 GLFW 设置 OpenGL NetBeans 项目

    我正在尝试在 Ubuntu 上设置 OpenGL 开发环境 我安装了包括 GLFW 在内的所有库 因为我不想使用 GLUT GLEW 库也已安装 我正在尝试将其全部设置在 NetBeans 中 我从未使用过它之前和现在我得到 对 glfwI
  • 使用 bash 我需要删除文件名中文件扩展名之前的尾随空格

    我有数百个文件 它们看起来类似于 QDN34 Unit5 mark up Judy pdf QDN34 Unit7 mark up Judy pdf file with two character ext ai file with dot