gpt4 book ai didi

linux - 从文件名中提取数字

转载 作者:太空狗 更新时间:2023-10-29 11:29:27 25 4
gpt4 key购买 nike

我有一堆文件,它们都有名称、序列号和扩展名。我想提取这个序列号和扩展名。它们看起来像这样:

photo-123.jpg
photo-456.png
photo-789.bmp

等等

我想运行一个 bash 脚本来提取这些序列号并以这种方式将它们放在一个文件中:

123
456
789

等等

请注意,并非所有照片都具有相同的扩展名(bmppngjpg),但它们都以 photo 开头-

最佳答案

你可以使用 parameter substitution :

$ ls
photo-123.jpg photo-456.png photo-7832525239.bmp photo-789.bmp

$ for file in *; do
[[ -f "$file" ]] || continue
[[ $file == "num.log" ]] && continue
file=${file%.*} && echo "${file#*-}"
done > num.log

$ ls
num.log photo-123.jpg photo-456.png photo-7832525239.bmp photo-789.bmp

$ cat num.log
123
456
7832525239
789

${parameter#word}start 中删除最短 匹配,${parameter##word}start 中删除longest 匹配。相反,${parameter%word} 将从end 中删除shortest 匹配,${parameter%%word} 将从end 中删除longest 匹配。

或者,如果目录中没有文件,您可以阅读 nullglob 而不是检查文件是否存在。 (感谢 Adrian Frühwirth 的重要反馈)

关于linux - 从文件名中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23434479/

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