在阅读文本文件时,shell是否将<space>与<new line>混淆了?

0x9*_*x90 0 linux shell scripting ubuntu-11.04

我试图运行这个脚本:

for line in $(cat song.txt)
do echo "$line" >> out.txt
done
Run Code Online (Sandbox Code Playgroud)

在ubuntu 11.04上运行它

当"song.txt"包含:

I read the news today oh boy
About a lucky man who made the grade
Run Code Online (Sandbox Code Playgroud)

运行脚本后,"out.txt"看起来像这样:

I
read
the
news
today
oh
boy
About
a
lucky
man
who
made
the
grade
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*nov 6

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

cat song.txt | while read line
do
    echo "$line" >> out.txt
done
Run Code Online (Sandbox Code Playgroud)

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

while read line
do
    echo "$line"
done < song.txt > out.txt
Run Code Online (Sandbox Code Playgroud)

  • 在while循环之外进行重定向更有效:`... | 读线; 回声"$ line"; 完成> out.txt` (2认同)