开发者

How to read entire line from bash

I have a file file.txt with contents like

i love this world

I hate stupid managers
I love linux

I have MS

When I do the following:

for line in `cat file.txt`; do
echo $line
done

It gives output like

I
love
this
world
I
..
..

But I need the output as entire lines like below — any thoughts ?

开发者_StackOverflow社区i love this world

I hate stupid managers
I love linux

I have MS


while read -r line; do echo "$line"; done < file.txt


As @Zac noted in the comments, the simplest solution to the question you post is simply cat file.txt so i must assume there is something more interesting going on so i have put the two options that solve the question as asked as well:

There are two things you can do here, either you can set IFS (Internal Field Separator) to a newline and use existing code, or you can use the read or line command in a while loop

IFS="
"

or

(while read line ; do
    //do something
 done) < file.txt


I believe the question was how to read in an entire line at a time. The simple script below will do this. If you don't specify a variable name for "read" it will stuff the entire line into the variable $REPLY.

cat file.txt|while read; do echo $REPLY; done

Dave..


You can do it by using read if the file is coming into stdin. If you need to do it in the middle of a script that already uses stdin for other purposes, you can temporarily reassign the stdin file descriptor.

#!/bin/bash
file=$1 

# save stdin to usually unused file descriptor 3
exec 3<&0

# connect the file to stdin
exec 0<"$file"

# read from stdin 
while read -r line
do
    echo "[$line]"
done

# when done, restore stdin
exec 0<&3


Try

(while read l; do echo $l; done) < temp.txt

read: Read a line from the standard input and split it into fields.

Reads a single line from the standard input, or from file descriptor FD if the -u option is supplied. The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with any leftover words assigned to the last NAME. Only the characters found in $IFS are recognized as word delimiters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜