從名稱中包含空格的目錄複製文件

從名稱中包含空格的目錄複製文件

這就是我嘗試過的。

inputFile=$(zenity --file-selection --title "Test" --text "Please select the file for analysis." | sed -e "s/ /\\\ /g")

我執行了sed用 a 和一個空格替換空格的操作,\以使複製命令起作用。然後,從 Zenity 文件選擇 GUI 中,我選擇了一個文件,其中的inputFile值為/home/username/Documents/Learning\ and\ Development/testfile.txt.

現在,當我嘗試將此文件複製到我的工作目錄時

cp $inputFile .

仍然回傳錯誤,

cp: cannot stat ‘/home/user/Documents/Learning\\’: No such file or directory
cp: cannot stat ‘and\\’: No such file or directory
cp: cannot stat ‘Development/WhatsApp.apk’: No such file or directory

有什麼辦法可以繞過這個嗎?其實我正在寫一個程式。所以我不想告訴用戶重命名他們的資料夾名稱以避免空格。

答案1

您可以輕鬆地做到這一點,用雙引號引起來:

cp "$inputFile" /destination/

將字元括在雙引號 ('"') 中會保留引號內所有字元的字面值,但 '$'、'`'、'\' 除外,閱讀更多:http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html

答案2

您可以在出現空格的地方新增 *,然後可以像這樣完成複製

 cp  /home/user/users*tst.txt  /home/user/Downloads

您要將使用者 tst.txt 從主資料夾複製到下載資料夾的位置

相關內容