Linux Shell reads a line

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.