简体   繁体   English

将文件名的第一部分移到文件扩展名的末尾

[英]Move first part of a file name to the end, before the file extension

Got the following code which removes 1234- from the start of a file name 得到了以下代码,从文件名的开头删除了1234-

rename -v "s/^1234-//g" *.***

Input: 输入:

1234-test1.test2.jpg 1234-test1.test2.jpg

Output: 输出:

test1.test2.jpg test1.test2.jpg

And this bit of code which add -1234 to the end of the file name 这段代码将-1234添加到文件名的末尾

for file in *.jpg; do echo $(basename $file .jpg)-1234; done

Input: 输入:

test1.test2.jpg test1.test2.jpg

Output: 输出:

test1.test2-1234.jpg test1.test2-1234.jpg

I´m looking for a way to combine these 2 commands into one single script, but also somehow avoid the second bit of code to keep adding -1234 for every time its run once its there, if possible. 我正在寻找一种将这两个命令组合到一个脚本中的方法,但是如果可以的话,还要以某种方式避免第二次代码在每次运行时都添加-1234。

This assumes all the files are .jpg : 假设所有文件都是.jpg

rename -v "s/^1234-(.+)(\.jpg)/$1-1234$2/" *.*

This matches the whole file name but captures just the part after 1234- in 2 groups. 这与整个文件名匹配,但仅捕获 1234-之后的2个部分。 The $1 and $2 area back-references to the captured parts. $1$2区域对捕获的部分进行反向引用。

This would to it: 这样做:

for file in *.jpg; do
   basename=${file%.*}               # Get the basename without using a subprocess.
   extension=${file##*.}             # Get the extension if you want to add *.JPG in the for, can be skipped if only *.jpg.

   newname=${basename#1234-}         # Remove "1234-" in front of basename.
   test "$basename" = "$newname" &&  # If basename did not start with "1234-", skip this file.
     continue  

   newname=${newname%-1234}          # Remove an eventual "-1234" at the end of newname.
   newname="${newname}-1234"         # Add "-1234" at the end of newname.
   newname="$newname.$extension"     # Restore extension.
   echo mv "$file" "$newname"        # echo rename command.
done

If you are happy with the output, remove the echo in the last line. 如果您对输出感到满意,请删除最后一行中的回显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM