2016-10-17 22 views
0

替換文件名的數字我有多個文件,大約150,有名稱不匹配供應商的要求。例如文件名是:在UNIX(BASH)

company_red001.p12 
company_red002.p12 
. 
. 
. 
. 
company_red150.p12 

我需要重命名的所有文件,使得24被添加到每個數字順序和不存在前述零的並且該company_成分被去除。

red25.p12 
red26.p12 
red27.p12 
. 
. 
. 
red150.p12 

我在bash中使用的循環去除company_組件,但想的東西,同時執行所有的變化,因爲我有在片刻通知執行此。

例如:

#!/bin/bash 

n = 24 

for file in company_red* 

do 

    new_name=$file$n 
    n=$(($+1)) 
    mv -i $file $new_name 

done 

例2

#!/bin/bash 

for f in company_red* 

do mv "$f" "${f/company_red/red}"; 

done 
+0

歡迎堆棧溢出..'我使用了一個for循環in..' - 請提供代碼示例中的問題,從您的部分顯示至少一些努力:) – sjsam

+1

我道歉,這是我的工作電腦上完成,我不能逐字產生我的努力,在樣品上方沒有工作。 – mick

+0

謝謝大家,問題解決了。 – mick

回答

0

最大的可能是這一個可能是罰款:)

# printf is used to emulate a lot of files 
for f in $(printf "company_red%03d.p12\n" {1..150}) 
do 
    # get the filename 
    n="$f" 
    # remove extension 
    n="${n%.*}" 
    # remove leading letters 
    n="${n##*[[:alpha:]]}" 
    # add 24, 10# is used to consider the 10-based number 
    n="$((10#$n + 24))" 
    # construct new filename 
    g="red${n}.p12" 
    echo mv "$f" "$g" 
done 

這可能是一個簡化位

for f in $(printf "company_red%03d.p12\n" {1..150}) 
do 
    # take the number from the specific, fixed position 
    n="${f:11:3}" 
    # everything below is the same as in the previous example 
    n="$((10#$n + 24))" 
    g="red${n}.p12" 
    echo mv "$f" "$g" 
done 

最後,這可能是又兩次簡化 - 只是逃避使用$n$g的:

for f in $(printf "company_red%03d.p12\n" {1..150}) 
do 
    echo mv "$f" "red$((10#${f:11:3} + 24)).p12" 
done 

但是,這可能會使代碼的理解和支持複雜化。

0

務必:

for file in *.p12; do 
    name=${file#*_} ## Extracts the portion after `_` from filename, save as variable "name" 
    pre=${name%.*} ## Extracts the portion before extension, save as "pre" 
    num=${pre##*[[:alpha:]]} ## Extracts number from variable "pre" 
    pre=${pre%%[0-9]*} ## Extracts the alphabetic portion from variable "pre" 
    suf=${name##*.} ## Extracts the extension from variable "name" 
     echo mv -i "$file" "${pre}""$(printf '%d' $((10#$num+24)))"."${suf}" ## Doing arithmetic expansion for addition, and necessary formatting to get desired name 
done 

輸出:

mv -i company_red001.p12 red25.p12 
mv -i company_red002.p12 red26.p12 

以上是乾式運行,刪除echo如果您滿意要做重命名:

for file in *.p12; do 
    name=${file#*_} 
    pre=${name%.*} 
    num=${pre##*[[:alpha:]]} 
    pre=${pre%%[0-9]*} 
    suf=${name##*.} 
     mv -i "$file" "${pre}""$(printf '%d' $((10#$num+24)))"."${suf}" 
done