2017-10-10 75 views
3

好吧,我有一個功能,將有作爲參數字符串,它會輸出一個新的字符串有任何空間'"巴什 - 重命名有「文件中它

function rename_file() { 

local string_to_change=$1 
local length=${#string_to_change} 
local i=0 
local new_string=" " 
local charac 

for i in $(seq $length); do 
    i=$((i-1)) 
    charac="${string_to_change:i:1}" 

    if [ "$charac" != " " ] && [ "$charac" != "'" ] && [ "$charac" != """ ]; then #Here if the char is not" ", " ' ", or " " ", we will add this char to our current new_string and else, we do nothing 

     new_string=$new_string$charaC#simply append the "normal" char to new_string 

    fi 

done 

echo $new_string #Just print the new string without spaces and other characters 
} 

但我就是無法測試,如果一個字符是",因爲它是行不通的。如果我打電話給我的函數

rename_file (file"n am_e) 

它只是打開>並等待我進入..任何幫助?

+0

你試過rename_file(文件\「N am_e) –

+0

如果鍵入(或放在一個腳本)'rename_file(文件」 N AME)',那麼你有沒有調用的函數'的說法'文件rename_file' 「n ame」。相反,你已經輸入了一個字符串的開頭,並且bash提示你並等待你終止字符串。嘗試'rename_file file \「n a'' –

+0

不確定你是否想要一個純粹的bash解決方案,但我可以建議一個單一的班輪嗎? :)'new_string = $(echo $ string | sed -e's///'-e's /,//'-e's /「//')'。另外,將'$ 1'改爲'$ {@}'作爲一個函數參數,否則它將在空格上打破 – favoretti

回答

5

將名稱放在單引號中。

rename_file 'file"n am_e' 

如果你想測試單引號,將它用雙引號:

rename_file "file'n am_e" 

來測試,把它們放在雙引號和逃避內部雙引號:

rename_file "file'na \"me" 

另一種選擇是使用一個變量:

quote='"' 
rename_file "file'na ${quote}me" 

此外,您不需要在shell函數的參數周圍放置括號。它們被稱爲普通命令,參數在同一命令行上用空格分隔。

而且您不需要該循環來替換字符。

new_string=${string_to_change//[\"\' ]/} 

本語法的說明,請參見Parameter Expansion Bash的手冊中的

+2

我懷疑OP實際上並不需要在文件名中包含parens,並且指出它們在函數調用中不需要它可能會有幫助 –

+0

啊,這個實際上相當酷!我忘記了自己的擴展,在評論中提供了基於sed的解決方案OP。 – favoretti

+0

@WilliamPursell謝謝,更新了答案 – Barmar