zoukankan      html  css  js  c++  java
  • shell下读取文件数据

    while和for对文件的读取是有区别的:

    1. for对文件的读是按字符串的方式进行的,遇到空格什么后,再读取的数据就会换行显示
    2. while对文件读是逐行读完后跳转到下行,while相对for的读取很好的还原数据原始性
     
    正常情况下我们按行读取文件都直接用while来实现的,但是在某些特殊情况下使用while可能会出现问题(例如while循环里嵌套sshpass命令时,while在从文件读取数据时,只读取第一行数据就自动退出了,并且退出状态为0),此时我们就必须要使用for循环来逐行从文件读取数据。
    目前有info.txt这个文件,里面存储了以空格分割的IP、用户名、密码等信息。
    [root@imzcy ~]# cat info.txt
    192.168.1.1 zhangsan 123456
    192.168.1.2 lisi 111111
    192.168.1.3 wangwu 22222
     
     
    1.我们按照while的习惯来写脚本尝试使用for读取文件每行数据(当然下面这个脚本是有问题的)。
    [root@imzcy ~]for i in $(cat info.txt);do echo $i ;done
    for循环会以空格分割读入的数据,所以输出为:
    192.168.1.1
    zhangsan
    123456
    192.168.1.2
    lisi
    111111
    192.168.1.3
    wangwu
    22222
    2.shell下使用for循环来按行从文件读入数据(每次读入一整行数据)
    #!/bin/bash
    f=/root/info.txt
    l=`cat $f |wc -l`
     
    for i in `seq 1 $l`;
    do
      cat $f |head -n $i |tail -n 1
      sleep 1
    done
    执行结果为:
    192.168.1.1 zhangsan 123456
    192.168.1.2 lisi 111111
    192.168.1.3 wangwu 22222
     
    cat $f |head -n $i |tail -n 1 获取某一行
    while循环读方式
    #!/bin/bash
    cat filename | while read line;do
      echo $line
    done
    192.168.1.1 zhangsan 123456
    192.168.1.2 lisi 111111
    192.168.1.3 wangwu 22222
    while循环读方式2
    #/bin/sh
    while read line;do
      echo $line
    done < filename
    while 死循环
    while [ "1" = "1" ]
    do
      #do something
    done
     
    将info.txt文件中存储的信息使用逗号分隔,然后使用for循环读取文件内容
    cat info.txt
    192.168.1.1,zhangsan,123456
    192.168.1.2,lisi,111111
    192.168.1.3,wangwu,22222
     
    ips=`cat info.txt`
    for ip in $ips;do
      echo $ip
      ip_info=(${ip//,/ })
      if [ ${#ip_info[@]} -eq 3 ];then
        #do something
      fi
    done
     
     
     
  • 相关阅读:
    [leetcode]95 Unique Binary Search Trees II (Medium)
    [leetcode] 96 Unique Binary Search Trees (Medium)
    [leetcode] 72. Edit Distance (hard)
    [leetcode] 120. Triangle (Medium)
    [leetcode] 63. Unique Paths II (medium)
    [OpenGL] 不规则区域的填充算法
    [leetcode] 64. Minimum Path Sum (medium)
    ESLint入坑
    报错:for..in loops iterate over the entire prototype chain, which is virtually never what you want.
    vue解决seo优化之预渲染prerender-spa-plugin
  • 原文地址:https://www.cnblogs.com/mianbaoshu/p/14009550.html
Copyright © 2011-2022 走看看