用bash命令行批量修改文件名称

前言:如果存在大量同类型的文件需要修改名称时,可以通过命令行来修改。Mac系统也自带批量修改的工具,但是不好用。其实现在这种工作可以直接询问AI助手,然后修改它给的脚本即可。

使用到的工具:Warp模拟终端,首先该软件还在测试阶段,其次Mac独占,最后它需要登录账号使用(就必然会收集一部分信息),比较看重隐私的朋友就不要使用了,娱乐和学习则是非常好用。

官网:https://www.warp.dev/
使用参考:https://pwa.sspai.com/post/79262

本次我们直接尝试内嵌的AI助手,写脚本时就不用搜索引擎,直接问它就可以,目前每天可以免费提问100次。提问:how do I rename a bunch of jpg files


Warp AI的回答

把代码复制出来,其实是可以直接用的。并且他还解释了代码,以及给脚本文件授予可执行权限后,再执行。

#!/bin/bash

# Set the directory where the JPG files are located
directory="/path/to/jpg/files"

# Set the new name prefix
new_name_prefix="new_name_"

# Loop through each JPG file in the directory
for file in "$directory"/*.jpg; do
   # Get the current file name
   current_name=$(basename "$file")

   # Generate the new file name
   new_name="${new_name_prefix}${current_name}"

   # Rename the file
   mv "$file" "$directory/$new_name"
done

但是我想要重名为001、002、003这种格式的,继续提问:how do I rename file to align them in numebr sequence


Warp AI的回答对齐排序

仔细观察,其中“$(printf %03d $start_number)”这一句,就实现了排序并且是对齐的。

#!/bin/bash

# Set the directory where the files are located
directory="/path/to/files"

# Set the prefix for the new file names
prefix="file"

# Set the starting number for the sequence
start_number=1

# Loop through each file in the directory
for file in "$directory"/*; do
   # Get the current file name
   current_name=$(basename "$file")

   # Generate the new file name with aligned number sequence
   new_name="${prefix}_$(printf "%03d" "$start_number")"

   # Rename the file
   mv "$file" "$directory/$new_name"

   # Increment the sequence number
   ((start_number++))
done

最后,我不想要每次都修改文件夹路径,直接拷贝脚本到对应文件夹,再执行即可。更进一步的话,我们可以继续提问,比如如何执行脚本时接受一个文件路径参数(实际得用英文提问),这样就是更高级的玩法了。

#!/bin/bash

# prefix 表示前缀
prefix=""
# starting 表示新的文件名称从哪个数字开始
starting=1

for file in *.jpg; do
  # new_name 表示新的文件名称
  new_name="${prefix}$(printf "%03d" $starting)".jpg

  # mv 开始修改文件名称
  mv "$file" "$new_name"

  # 递增文件编号
  ((starting++))
done
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容