• shell按行读取文件


    这工作小半年了发现以前学的那么多流弊技能都不怎么用,倒是shell用的很多,自己已经从shell小菜鸟一步步走过来,已经要变成大菜鸟=。=
    经常需要用shell按行读取配置文件,自己在上面踩了很多坑,可依然没长记性,故记录下来。先创建一个测试用例toy.txt;

    [VasiliShi@ZXXS workplace]$ cat toy.txt 
    this is 1
    this is 2
    this is 3
    
    

    使用while读取###

    使用while读取文件时候需要配合read,利用read读取文件时,每次调用read命令都会读取文件中的"一行"文本。
    当文件没有可读的行时,read命令将以非零状态退出.

    echo "=====this is method one====="
    cat toy.txt | while read line
    do
       echo $line
    done
    
    

    输出:

    =====this is method one=====
    this is 1
    this is 2
    this is 3
    
    

    使用for读取###

    使用for读取时,自动按空格(包括:空格,制表符),作为间隔符。
    如果输入文本每行中没有空格,则line在输入文本中按换行符分隔符循环取值.

    echo "=====this is method two====="
    for line in `cat toy.txt`
    do
       echo $line
    done
    

    输出:

    =====this is method two=====
    this
    is
    1
    this
    is
    2
    this
    is
    3
    

    正如上面所说,输出结果都被空格拆散开了,那么该如何解决呢?可以设置IFS=$' ' 作为分隔符

    IFS=$'
    ' #
    echo "=====this is method two====="
    for line in `cat toy.txt`
    do
       echo $line
    done
    
  • 相关阅读:
    BZOJ 1707 [Usaco2007 Nov]tanning分配防晒霜
    BZOJ2697:特技飞行
    Bridging signals(NlogN最长上升子序列)
    HDU 4291 A Short problem(矩阵+循环节)
    计蒜之道 初赛第一场B 阿里天池的新任务(简单)
    1008: [HNOI2008]越狱
    1022: [SHOI2008]小约翰的游戏John
    1192: [HNOI2006]鬼谷子的钱袋
    2456: mode
    BZOJ-1968
  • 原文地址:https://www.cnblogs.com/wxshi/p/8034732.html
Copyright © 2020-2023  润新知