在读取文本文件时,shell是否将<space>与<new line =“”>混淆了?</new> </space>

时间:2011-11-11 11:40:58

标签: 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
who
made
the
grade

有谁能告诉我这里我做错了什么?

3 个答案:

答案 0 :(得分:6)

对于每行输入,您应使用while read,例如:

cat song.txt | while read line
do
    echo "$line" >> out.txt
done

更好(更有效率)将是以下方法:

while read line
do
    echo "$line"
done < song.txt > out.txt

答案 1 :(得分:1)

这是因为for命令从列表中获取每个单词(在您的情况下,song.txt文件的内容),是否单词由空格或换行符分隔。

这里有什么误导你,你的变量名是linefor仅适用于文字。重新阅读line更改word的脚本,这应该是有道理的。

答案 2 :(得分:1)

在for-each-in循环中,指定的列表被假定为空格分隔。白色空间包括空格,换行符,制表符等。在您的情况下,列表是文件的整个文本,因此,循环运行文件中的每个单词。