• Linux shell 读取一行



    方法一
    通过指定IFS--Internal Field Separator,IFS默认情况下是<space><tab><newline>,可以在脚本中设定IFS值
    DEMO 1
    $cat t1.txt
    abcfd
    $cat test_IFS.sh
    #! /bin/sh
    IFS="c"
    for LINE in `cat t1.txt`
    do
    echo $LINE
    done
    $sh test_IFS.sh
    ab
    fd
    这里需要读取一行只需将IFS=" "设置为换行符即可。
    DEMO2
    $cat t1.txt
    a b
    c d
    不设置IFS
    $ cat test_IFS.sh
    #! /bin/sh
    #IFS=" "
    for LINE in `cat t1.txt`
    do
    echo $LINE
    done
    $sh test_IFS.sh
    a
    b
    c
    d
    设置IFS=" "
    $ cat test_IFS.sh
    #! /bin/sh
    IFS=" "
    for LINE in `cat t1.txt`
    do
    echo $LINE
    done
    $sh test_IFS.sh
    a b
    c d
    这样就可以达到读取一行的目的了
    方法2
    利用read命令,从标准输入读取一行,根据IFS进行切分并相应的变量赋值,这里为了我们故意将IFS设置为&,来进行演示
    DEMO3
    $cat test_read.sh
    #! /bin/sh
    IFS="&"
    printf "Enter your name, rank, serial num:"
    read name rank serno
    printf "name=%s rank=%s serial num=%s" $name $rank $serno
    $sh test_read.sh
    Enter your name, rank, serial num:zk&1&123
    name=zk
    rank=1
    serial num=123
    所以我们知道read每次是读一行,因此使用read命令就好了
    DEMO4
    $cat readline_1.sh
    #! /bin/sh
    cat t1.txt | while read LINE
    do
    echo $LINE
    done
    $sh readline_1.sh
    a b
    c d
    这里是通过文件重定向给read处理
    方法3
    用read去读取文件重定向
    DEMO5
    $cat readline_2.sh
    #! /bin/sh
    while read LINE
    do
    echo $LINE
    done < t1.txt
    $sh readline_2.sh
    a b
    c d
    推荐使用方法3

    zhaisongfang
  • 相关阅读:
    cmd命令操作Mysql数据库
    可编程作息时间控制器设计
    博客第一天
    PRML 1: Gaussian Distribution
    KMP String Matching Algorithm
    Reinstall Ubuntu 14.04
    Computability 4: Decidability and R.E. Sets (I)
    Consumer-Producer Problem
    Compile the Linux Kernel
    Introduction to Linux Kernel
  • 原文地址:https://www.cnblogs.com/zhaisongfang/p/14156899.html
Copyright © 2020-2023  润新知