透過 shell 腳本分割“檔案”和“帶空格的目錄名稱”

透過 shell 腳本分割“檔案”和“帶空格的目錄名稱”

我有一個名為的文件,Files.txt其內容如下:

TestApp/Resources/Supporting Files/main.m
TestApp/Resources/Supporting Files/AppDelegate.h
TestApp/Resources/Supporting Files/AppDelegate.m

我正在提取文件和目錄名稱,如下所示,並將它們傳遞給另一個進程。

files=$(cat Files.txt)

for item in $files ; do    
  dn=$(dirname $item)

  printf $item
  printf "\n"
  printf $dn
  printf "\n\n"

  # passing to another process
done

然而,這讓我這樣:

TestApp/Resources/Supporting
TestApp/Resources

Files/main.m
Files

TestApp/Resources/Supporting
TestApp/Resources

Files/AppDelegate.h
Files

TestApp/Resources/Supporting
TestApp/Resources

Files/AppDelegate.m
Files

我需要的是這樣的:

TestApp/Resources/Supporting Files/main.m
TestApp/Resources/Supporting Files

TestApp/Resources/Supporting Files/AppDelegate.h
TestApp/Resources/Supporting Files

TestApp/Resources/Supporting Files/AppDelegate.m
TestApp/Resources/Supporting Files

我嘗試\Files.txtas 中加入空格前綴:

TestApp/Resources/Supporting\ Files/main.m

%20作為:

TestApp/Resources/Supporting%20Files/main.m

沒有運氣!

答案1

  1. for循環迭代不是線條
  2. 總是引用你的"$variables"(除非你確切知道什麼時候不引用)
while read -r item ; do    
  dn=$(dirname "$item")

  printf "%s\n" "$item"
  printf "%s\n" "$dn"

  # pass "$item" and "$dn" to another process
done < Files.txt

答案2

您需要設定欄位分隔符號:

OIFS=$IFS  
IFS=$'\n'

files=$(cat Files.txt)

for item in $files ; do    
  dn=$(dirname $item)
  printf $item
  printf "\n"
  printf $dn
  printf "\n\n"

  # passing to another process
done

IFS=$OIFS

輸出:

[me@localhost test]$ ./test.sh 
TestApp/Resources/Supporting Files/main.m
TestApp/Resources/Supporting Files

TestApp/Resources/Supporting Files/AppDelegate.h
TestApp/Resources/Supporting Files

TestApp/Resources/Supporting Files/AppDelegate.m
TestApp/Resources/Supporting Files

解釋: http://en.wikipedia.org/wiki/Internal_field_separator

$IFS變數定義輸入如何拆分為標記,預設為空格、製表符和換行符。由於您只想在換行符上拆分,因此$IFS需要暫時更改該變數。

相關內容