我有一个名为的文件,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
需要临时更改该变量。