Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux shell是否会混淆<;空间>;与<;新生产线>;当读取文本文件时?_Linux_Shell_Scripting_Ubuntu 11.04 - Fatal编程技术网

Linux shell是否会混淆<;空间>;与<;新生产线>;当读取文本文件时?

Linux shell是否会混淆<;空间>;与<;新生产线>;当读取文本文件时?,linux,shell,scripting,ubuntu-11.04,Linux,Shell,Scripting,Ubuntu 11.04,我尝试运行此脚本: for line in $(cat song.txt) do echo "$line" >> out.txt done 在ubuntu 11.04上运行它 当“song.txt”包含以下内容时: I read the news today oh boy About a lucky man who made the grade 运行脚本后,“out.txt”如下所示: I read the news today oh boy About a lucky man

我尝试运行此脚本:

for line in $(cat song.txt)
do echo "$line" >> out.txt
done
在ubuntu 11.04上运行它

当“song.txt”包含以下内容时:

I read the news today oh boy
About a lucky man who made the grade
运行脚本后,“out.txt”如下所示:

I
read
the
news
today
oh
boy
About
a
lucky
man
who
made
the
grade

有人能告诉我我做错了什么吗

这是因为
for
命令从给定的列表(在您的例子中是
song.txt
文件的内容)中获取每个单词,无论这些单词是用空格还是换行符分隔的


这里误导您的是,您的for变量名是
for
仅适用于单词。通过
word
重新阅读脚本更改
,它应该是有意义的。

对于每行输入,您应该在阅读时使用
,例如:

cat song.txt | while read line
do
    echo "$line" >> out.txt
done
更好(更有效)的方法是以下方法:

while read line
do
    echo "$line"
done < song.txt > out.txt
读取行时
做
回音“$line”
完成out.txt

在for each In循环中,指定的列表假定为空格分隔。空白包括空格、新行、选项卡等。在您的情况下,列表是文件的全部文本,因此,循环针对文件中的每个单词运行。

这两行之间有什么区别?它以新行打印每个单词,而不是以新行打印每行。在while循环之外执行重定向更有效:
。|读行时;做回显“$line”;done>out.txt
@glenn也许,在这种特殊情况下看不出有多大区别