[英]Bash script to rename files and increment number in the file name by N
我在創建靜態網站演示的目錄中有一堆帶編號的頁面。
他們是:
等等。
有時,我需要添加一兩個屏幕並將其插入中間的某個位置。 然后,我必須手動將Wizard15重命名為Wizard16,依此類推。
我希望有一個腳本可以讓我重命名以某個數字開頭的文件(例如,wizard3或Wizard19等),以及可以增加多少數字(如果我要添加兩個,三個或更多新屏幕的話)在流中)。
我一點都不了解bash,否則我會自己嘗試。
這應該工作
filename=$1 #Filename
filenumber=$2 #file number from where you want to rename.
count=$3 #number of files
lastfile=$4 #Last filenumber in the folder
for ((i=lastfile; i>=$filenumber; i--))
do
mv $filename$i $filename`expr $i + $count`
done
您可以如下運行
./rename wizard 15 3 30
將此腳本放在您的目錄中。 例如,它將具有名稱script.sh
請先在某個文件夾中進行測試!
#!/bin/bash
# output files in dir
echo "------------------------------"
ls -la
echo "------------------------------"
echo -n "Enter starting number for modify: "
read old_starting_num
echo -n "Enter last number for modify: "
read old_last_num
# Check are there files from the range
for (( i=$old_starting_num; i<=old_last_num; i++))
do
if [[ ! -f wizard$i.html ]]
then
echo "ERROR: number from the range is not exist!"
exit 1
fi
done
# Make sure that last number => starting number
count=$(( $old_last_num - $old_starting_num ))
if [[ $count -ge 0 ]]
then
echo -n "Enter NEW starting number: "
read new_starting_num
diff=$(( $new_starting_num - $old_starting_num ))
for i in $(seq $old_starting_num $old_last_num)
do
k=$(( $i + $diff ))
mv -i -v wizard$i.html wizard$k.html
done
else
echo "ERROR: starting number > then last number!"
exit 1
fi
授予執行權限並運行:
chmod +x script.sh
./script.sh
它是如何工作的:
[root@al]# ./script.sh
------------------------------
итого 24
drwxr-xr-x 2 root root 4096 Сен 11 18:52 .
drwxr-xr-x. 27 root root 4096 Сен 11 18:16 ..
-rwxr-xr-x 1 root root 832 Сен 11 18:52 script.sh
-rw-r--r-- 1 root root 0 Сен 11 18:18 wizard1.html
-rw-r--r-- 1 root root 0 Сен 11 17:29 wizard5.html
-rw-r--r-- 1 root root 0 Сен 11 18:37 wizard6.html
-rw-r--r-- 1 root root 0 Сен 11 18:37 wizard7.html
------------------------------
Enter starting number for modify: 5
Enter last number for modify: 6
Enter NEW starting number: 20
«wizard5.html» -> «wizard20.html»
«wizard6.html» -> «wizard21.html»
要么
[root@al]# ./script.sh
------------------------------
итого 12
drwxr-xr-x 2 root root 4096 Сен 13 15:44 .
drwxr-xr-x. 28 root root 4096 Сен 12 09:03 ..
-rwxr-xr-x 1 root root 928 Сен 13 15:44 script.sh
-rw-r--r-- 1 root root 0 Сен 13 09:38 wizard1.html
-rw-r--r-- 1 root root 0 Сен 13 09:31 wizard20.html
-rw-r--r-- 1 root root 0 Сен 13 09:38 wizard21.html
-rw-r--r-- 1 root root 0 Сен 13 09:38 wizard7.html
------------------------------
Enter starting number for modify: 20
Enter last number for modify: 23
ERROR: number from the ranage is not exist!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.