gpt4 book ai didi

Linux 脚本 : mass rename of files with whitespaces

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:32:04 26 4
gpt4 key购买 nike

我写了一个脚本来一次重命名几个文件并添加前导零。该脚本将要重命名的文件作为第一个参数,第二个参数是新名称,第三个参数是您可以提供新的扩展名

只要文件不包含空格(test asd 1.txt/test asd 2.txt),它实际上就可以工作,因为输出是:

~/Desktop $ gpRenameWithZero test\ asd\* test_ mp3
ls: cannot access test: No such file or directory
ls: cannot access asd*: No such file or directory
ls: cannot access test: No such file or directory
ls: cannot access asd*: No such file or directory

这是脚本:

#!/bin/bash
#rename a group of files with adding padding zero: gpRenameWithZero $1=filesToBeRenamed $2=newName $3=filetype: gpRenameWithZero \* newName_ jpg

#123 files -> length of number are 3 digits
numberOfDigits=$(ls $1| wc -l | xargs expr length)

#take extension from command line or take from filename
if [ $# -gt 2 ]; then
extension=$3
else
extension=$(ls -rt $1 | head -n 1 | rev | cut -d . -f1 | rev)
fi

#Preview
ls -rt $1 | cat -n | while read n f; do echo mv "$f" `printf "$2%0$numberOfDigits"d".$extension" $n`; done

read -p "Do you wish to rename [y/n]?" yn
case $yn in
[Yy]* ) ls -rt $1 | cat -n | while read n f; do mv "$f" `printf "$2%0$numberOfDigits"d".$extension" $n`; done;;
[Nn]* ) ;;
esac

我已经尝试过引用/双引号变量和参数,转义/不转义。

如何解决这个问题?或者是否有一个更简单的脚本,它将要重命名的文件、新名称和扩展名作为参数)来重命名多个文件。

最佳答案

你自己明白了,为什么是真的,评论是怎么说的:不要解析 ls 的输出.

在这种情况下,您需要处理以 NULL 结尾的文件名。这里有许多可以使用这种以 NULL 结尾的字符串的命令。

find命令可以使用 arg -print0 输出以 NULL 结尾的文件名或完全指定 -print "<format>\0" .

因为您想要按修改时间 (ls -rt) 对(编号)文件进行排序,所以您需要使用一些技巧。所以

  • find命令(GNU版本)可以打印出文件修改时间
  • 需要在这个时候对它们进行排序
  • 在切割时间字段后,您将得到一个排序的文件名列表

这可以通过以下命令来实现:

find . -mindepth 1 -maxdepth 1 -name "*" -printf "%T@:%p\0" |sort -zrn |sed -z 's/[^:]*://'
^^^^^^^^ ^^^ ^^^^^^^^^^
modification-time-in-seconds<colon>path-name<NULL>---+ | |
sort the NULL-terminated lines numerically (by time) ---+ |
remove the <time><colon> part, so only the filename remains ----------+

您可以将以上内容放入 bash 函数中以便于使用,例如:

sort_files_by_time() {
find "${1:-.}" -mindepth 1 -maxdepth 1 -type f -name "${2:-*}" -printf "%T@:%p\0" | sort -zrn | sed -z 's/[^:]*://'
}

上述函数可以接受两个可选参数:

  1. 查找的目录名(默认:.)
  2. filaname 搜索模式(默认:*)

现在您有一个按时间排序的文件名的 NULL 终止列表,需要阅读和使用它们。下一个循环

while IFS= read -d $'\0' -r path ; do
dir=$(dirname "$path")
file=$(basename "$path")

#do what you want

done < <(sort_files_by_time)

总是 双引号 "$variables"可以包含空格。

关于Linux 脚本 : mass rename of files with whitespaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25523203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com