gpt4 book ai didi

bash - 如何在 bash 中操作文件名?

转载 作者:行者123 更新时间:2023-12-04 18:36:52 26 4
gpt4 key购买 nike

我有一堆需要重命名的图像,所以我可以使用它们,我想知道如何做到这一点。
他们需要的方式是保留前 5 个,然后在第 6 个中我会写一个 1-3 的数字。我只知道前5个是静态的;在属于同一“家庭”的图片上,可用于比较,第 6 个字符未知。
例子:

12345random.jpg

12345randomer.jpg

0987654more_random.jpg

09876awesome.jpg

09876awesomer.jpg

09876awesomest.jpg

09876soawesomegalaxiesexplode.jpg


会成为。

12345.jpg

123452.jpg

09876.jpg

098761.jpg

098762.jpg


如果它只处理循环,这样就可以只重命名 3 张图片并跳过其余部分,那就太酷了。
我发现了一些关于将字母删除到某个点的东西,但没有任何用处,因为我在 bash 脚本方面很差。
这是我的方法,但有点糟糕,因为我尝试修改找到的脚本,但想法就在那里
//I could not figure how to remove the chars after 5th not the other way around
for file in .....*; do echo mv $file `echo $file | cut -c6-`; done

done
//problem also is that once the names conflict it produces only 1 file named 12345.jpg 2nd one will not be created
//do not know how to read file names to array
name=somefile
if [[ -e $name.jpg]] ; then
i=0
while [[ -e $name-$i.jpg]] ; do
let i++
done
name=$name-$i
fi
touch $name.jpg

最佳答案

你可以有:

new_file=${file%%[^0-9]*.jpg}.jpg

作为一个概念,您可以使用它来重命名文件:
for file in *.jpg; do
[[ $file == [0-9]*[^0-9]*.jpg ]] || continue ## Just a simple check.
new_file=${file%%[^0-9]*.jpg}.jpg
[[ -e $new_file ]] || continue ## Do not overwrite. Delete line if not wanted.
echo "Renaming $file to $new_file." ## Optional message.
mv -- "$file" "$new_file" || echo "Failed to rename $file to $new_file."
done

如果您要处理也包含目录名称的文件,则需要进行更多更改:
for file in /path/to/other/dirs/*.jpg *.jpg; do
base=${file##*/}
[[ $base == [0-9]*[^0-9]*.jpg ]] || continue
if [[ $file == */* ]]; then
new_file=${file%/*}/${base%%[^0-9]*.jpg}.jpg
else
new_file=${file%%[^0-9]*.jpg}.jpg
fi
[[ -e $new_file ]] || continue
echo "Renaming $file to $new_file."
mv -- "$file" "$new_file"
done

关于bash - 如何在 bash 中操作文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825417/

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