2014-01-08 105 views
0

我有一個名爲/input/temp的文件夾。在文件夾裏面我有很多文件。我需要找到Article_????_test_?????????.txt模式的文件,並按照以下格式進行替換。Unix shell腳本查找文件並按模式替換名稱

Article_????_?????????.txt 

下面是我試過和不工作的代碼:

echo "Please provide the file name Corresponding to DC..." 
read file 
ls $HOME/*.txt | grep $file 
if [ $? -eq 0 ] 
find . $file '*_Test_*' -exec bash -c 'mv $0 ${0/_Test/ }' {} \; 

    if [ $? -eq 0 ] 
find . $file -name "*.txt" -exec bash -c "mv {} \`echo {} | sed -e 's/[_TEST_]/_/g'\`" \; 
then 

我得到以下錯誤:

find: 0652-083 Cannot execute bash:: A file or directory in the path name does not exist. 
find: 0652-083 Cannot execute bash:: A file or directory in the path name does not exist. 

Bash可以不是我的平臺上執行。

+0

你正在使用什麼外殼?它是什麼系統? – slhck

回答

0

根據鏈路here: 這應該工作

ls -1 Article_????test?????????.txt|awk '{old=$0;gsub(/test/,"_",$0);system("mv \""old"\" "$0)}' 
+0

[你不應該像這樣解析'ls'輸出。](http://mywiki.wooledge.org/ParsingLs) – l0b0

+0

我可能知道爲什麼嗎? – Vijay

+0

上面鏈接的頁面解釋了它。 – l0b0

0

還嘗試了 '重命名' 命令。

rename 's/_test_/_/' *.txt 

您可以微調正則表達式...從您的代碼

0

更新:

cd $HOME 
find . -name '*_Test_*' |while read line 
do 
    echo mv ${line) ${line/_Test/} 
done 

如果你需要搜索的格局文章_ ???? 測試 ?????????。TXT,試試這個

cd $HOME 
find . -name 'Article_????_test_?????????.txt' |while read line 
do 
    echo mv ${line) ${line/_Test/} 
done 
1
  • 除非文件名是您可以使用if [ -e "$file" ]代替ls + grep + test正則表達式。
  • 當你做find . $file '*_Test_*'最後三個參數實際上是作爲文件或目錄在下面搜索!它會返回
    • 所有文件在當前目錄下,
    • 所有目錄中的文件$file路徑$file,如果它不是一個目錄,
    • 所有文件匹配*_Test_*或任何目錄他們的路徑,如果他們不是目錄。
  • 不需要bash - 您可以直接在-exec中運行mv。這只是額外的複雜性而沒有收益。
  • 使用$(command)而不是command更容易處理報價。每個$()都有一個單獨的引用上下文,因此您可以執行例如echo "$(command "$(c2 "argument with spaces")")"