
我有一個名為的文件,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.txt
as 中加入空格前綴:
TestApp/Resources/Supporting\ Files/main.m
並%20
作為:
TestApp/Resources/Supporting%20Files/main.m
沒有運氣!
答案1
for
循環迭代字不是線條- 總是引用你的
"$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
需要暫時更改該變數。