Linux Shell reads a line
Method One
By specifying IFS--Internal Field Separator
, by IFS
default <space><tab><newline>
, you can set a value in the script IFS
DEMO 1
$cat t1.txt abcfd $cat test_IFS.sh #! /bin/shIFS="c"for LINE in `cat t1.txt`do echo $LINEdone$sh test_IFS.sh abfd
You need to read a line here just to IFS="\n"
set the line break.
DEMO2
$cat t1.txt a bc d
Not setIFS
$ cat test_IFS.sh #! /bin/sh#IFS="\n"for LINE in `cat t1.txt`do echo $LINEdone$sh test_IFS.sh abcd
Set upIFS="\n"
$ cat test_IFS.sh #! /bin/shIFS="\n"for LINE in `cat t1.txt`do echo $LINEdone$sh test_IFS.sh a bc d
This will allow you to read a line.
Method 2
Use the read
command to read a line from the standard input, based on the IFS
partitioning and assign the corresponding variable, here for our intentional IFS
set to, for the &
demonstration
DEMO3
$cat test_read.sh #! /bin/shIFS="&"printf "Enter your name, rank, serial num:"read name rank sernoprintf "name=%s\nrank=%s\nserial num=%s" $name $rank $serno $sh test_read.sh Enter your name, rank, serial num:zk&1&123name=zkrank=1serial num=123
So we know that read
every time we read a line, it's okay to use the read
command.
DEMO4
$cat readline_1.sh #! /bin/shcat t1.txt | while read LINEdo echo $LINEdone$sh readline_1.sh a bc d
Here is a file redirection to read processing
Method 3
Use read
to read file redirection
DEMO5
$cat readline_2.sh #! /bin/shwhile read LINEdo echo $LINEdone < t1.txt$sh readline_2.sh a bc d
Recommended method of Use 3