2011-01-21 30 views
0

因此,我將再次發佈有關shell腳本的問題。Shell腳本:對文件執行cmd,並附加文件名處理

問題定義:對於一個目錄下的所有文件,例:

  • A_anything.txt,B_anything.txt,......

我想執行一個劇本,說 'CMD',他們每個人的,名爲像輸出文件:

  • A_result.txt,B_result.txt,......

此外,在這些輸出文件的第一線,我想有文件名原來的

'find -exec'util對我來說似乎無法提取部分文件名。

是否有人通過任何方式(shell,python,find等)知道此問題的解決方案?謝謝!

回答

2
cd /directory 
for file in *.txt ; do 
    newfilename=`echo "$file"|sed 's/\(.\+\)_.*/\1_result.txt/` 
    echo "$file" > "$newfilename" 
    your-command $file >> "$newfilename" 
done 

HTH

+1

+1儘管隨之而來的是小竅門。可以說,它應該是`* .txt`或甚至``A-Z] _ *。txt`在`for`行中,但是如果這些文件都在一個單獨的目錄中,這將起作用。 `你的命令`行可能也需要``$ files「``。我會使用一個單獨的名稱`$ file`而不是複數`$ files`,因爲在任何時候它都包含一個文件名,而不是幾個。 – 2011-01-21 14:01:54

+0

你說得對。糾正。 +1 – 2011-01-21 14:26:39

1

嗯,有這樣做(包括使用Perl,其中是這樣的格言)的方法不止一種,但也許我會寫這樣的:

find . -name '[A-Z]_*.txt' -type f -print0 | 
    xargs -0 modify_rename.sh 

然後我會寫這樣的腳本modify_rename.sh

#!/bin/sh 
for file in "[email protected]" 
do 
    dirname=$(dirname "$file") 
    basename=$(basename "$file" .txt) 
    leadname=${file%_*} 
    outname="$dirname/${leadname}_result.txt" 
    # Optionally check for pre-existence of $outname 
    { 
    # Optionally echo "$basename.txt" instead of "$file" 
    echo "$file" 
    # Does this invocation of CMD write to standard output? 
    # If not, adjust invocation appropriately. 
    CMD "$file" 
    } > "$outname" 
done 

這種分離的優點n轉換爲單獨的腳本操作的方式是,可以將重命名/修改操作與搜索過程分開檢出 - 這樣可以降低使用錯誤命令切換整個目錄結構的風險。

Bash有一些工具可以避免調用basenamedirname,但是符號很模糊,我覺得這些命令的名字很清晰。如果bash將它們作爲內置插件實現,我會很高興。還有很多其他方法可以獲取文件的前綴;這應該是安全的,即使在文件或目錄名稱中存在空格(製表符,換行符)也是如此,因爲仔細使用了雙引號。