我正在练习使用命令read
:
$ ls * | while read line; do printf "test %s\n" $line; done
test data1.txt
test data5.txt
test data6.txt
test data7.txt
它可以正常工作,但是
$ ls * | while read line; do file $line; done
data1.txt: cannot open `data1.txt' (No such file or directory)
data5.txt: cannot open `data5.txt' (No such file or directory)
data6.txt: cannot open `data6.txt' (No such file or directory)
data7.txt: cannot open `data7.txt' (No such file or directory)
data8.txt: cannot open `data8.txt' (No such file or directory)
文件名合法
$ ls
data1.txt data5.txt data6.txt data7.txt data8.txt
我的代码有什么问题。
答案 0 :(得分:2)
我怀疑您的文件未命名为"data1.txt"
,实际上更像是"data1.txt "
。请注意最后的微妙空间。这很可能是脚本中的一个很小的错字造成的。也可能是无法打印的字符的使用。您可以使用ls --quoting-style=shell-escape
进行检查。
示例:
$ touch "data1.txt "
$ touch "data2.txt"
$ echo "a" > "data3.txt "
$ ls data* | while read line; do file $line; done
data1.txt: cannot open (No such file or directory)
data2.txt: empty
data3.txt: cannot open (No such file or directory)
^
Notice the missing spaces
此行有几个问题:
ls
read
removes all leading and trailing whitespace characters。 这实际上是这里的主要问题 因此,如果您想解决read
问题,请执行以下操作:
$ ls data* | while IFS= read -r line; do file "$line"; done
data1.txt : empty
data2.txt: empty
data3.txt : ASCII text
^
Notice the spaces, this is due to read
但是正确的方法是:
$ for f in data*; do file "$f"; done
data1.txt : empty
data2.txt: empty
data3.txt : ASCII text