zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    学习笔记——Maven 如何处理传递性依赖
    gitlab 部署
    jenkins部署
    python 使用json格式转换
    php加载memcache
    centos6.5 apache+tomcat结合 负载均衡
    linux部署tomcat
    linux安装java环境
    kickstart安装
    cobbler部署
  • 原文地址:https://www.cnblogs.com/wxshi/p/8034732.html
Copyright © 2011-2022 走看看