While循环浏览文件名并删除空格 [英] While loop through file names and remove white space

查看:72
本文介绍了While循环浏览文件名并删除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用格式化文件名的方法.在下面,我有一个while循环,遍历文件名,并用 _ 替换空格,并在连字符未更改后保留所有内容.现在,问题正在遍历 find 命令的结果,以格式化名称.在脚本中运行时,输出如下:

I am currently working with formatting file names. Below I have a while loop that runs through file names and replaces white spaces with _ and keeps anything after the hyphen untouched. Now the issue is looping through the results of the find command in order to format the names. When running this in a script the out put is the following :

find: paths must precede expression: rename
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

rename.sh

rename.sh

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

/g')
       echo "mv '$file' '$new_file'"
  done < <(find ./ -type f rename)

之前的文件名:

'./My File - KeEp.txt'

后面的文件名:

'./my_file-KeEp.txt'

推荐答案

您打算重命名 find./-type f重命名中做什么?

查找是将其解释为(搜索)路径,然后告诉您不允许在参数后添加路径.

find is, as the error message is telling you, interpreting that as a path (to search) and then telling you that adding paths after arguments is not allowed.

话虽如此,正如@Beta在他的评论中指出的那样,在这里使用 while 循环是不必要的(而且很脆弱).

That being said, and as @Beta indicates in his comment, using a while loop here is unnecessary (and fragile).

尝试以下方法:

find ./ -type f -exec bash -c 'echo "mv \"$1\" \"$(echo "$1" | sed -re '\''s/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/'\'' -e '\''s/ /_/g'\'' -e '\''s/_-/-/g'\'')\""' - {} \;

或实际执行此操作:

find ./ -type f -exec bash -c 'mv "$1" "$(echo "$1" | sed -re '\''s/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/'\'' -e '\''s/ /_/g'\'' -e '\''s/_-/-/g'\'')"' - {} \;

解释一下:

  • '\''位是如何在单引号引起来的字符串中转义一个单引号(结束该字符串,转义一个单引号,然后再次启动该字符串).
  • -{} 中的-将填充 $ 0 参数,该参数是 bash 的第一个参数与 -c 和其他参数一起运行时.(否则脚本将需要使用 $ 0 而不是 $ 1 来访问文件名.)
  • the '\'' bit is how you escape a single quote inside a single quoted string (you end the string, escape a single quote and start the string again).
  • The - in - {} is to pad the $0 argument that is the first argument to bash when run with -c and other arguments. (Without that the script would need to use $0 instead of $1 to access the filename.)

哦,您的原始脚本在要扩展的变量周围使用了单引号,但是当您从echo命令中拉出双引号时,这是行不通的.

Oh, and your original script used single quotes around variables you wanted to have expanded, that wasn't going to work when you pulled the double quotes from the echo command out.

这篇关于While循环浏览文件名并删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆