• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Shell案例awk匹配、grep查找文件内的字符串6、去掉空行删除空行

武飞扬头像
哥们要飞
帮助1

描述
写一个 bash脚本以去掉一个文本文件 nowcoder.txt中的空行
示例:
假设 nowcoder.txt 内容如下:
abc

567


aaa
bbb

ccc

你的脚本应当输出:
abc
567
aaa
bbb
ccc

方法1:循环 打印非空的行

【循环读行,只能用while实现】

  1.  
    #!/bin/bash
  2.  
    while read line
  3.  
    do
  4.  
    if [[ -z $line ]]
  5.  
    then
  6.  
    # 删除空行
  7.  
    continue
  8.  
    fi
  9.  
    echo $line
  10.  
    done < nowcoder.txt

  1.  
    #!/bin/bash
  2.  
    while read line
  3.  
    do
  4.  
    if [[ $line == '' ]]
  5.  
    then
  6.  
    # 删除空行
  7.  
    continue
  8.  
    fi
  9.  
    echo $line
  10.  
    done < nowcoder.txt

  1.  
    #!/bin/bash
  2.  
    while read line
  3.  
    do
  4.  
    if [[ $line != '' ]]
  5.  
    then
  6.  
    # 删除空行
  7.  
    echo $line
  8.  
    fi
  9.  
    done < nowcoder.txt

方法2:awk实现

思路1:正则匹配空行&打印当前行内容/行号

  1.  
    #!/bin/bash
  2.  
    awk '!/^$/ {print $NF}'
  3.  
    #NF表示读出的行号,加$表示为当前行的内容

方法2:awk执行多条语句(用大括号括起来)

  1.  
    #!/bin/bash
  2.  
    awk '{if($0 != "") {print $0}}' < nowcoder.txt
  3.  
    #NF表示读出的行号,加$表示为当前行的内容

或管道

  1.  
    #!/bin/bash
  2.  
    cat nowcoder.txt | awk '{if($0 != "") {print $0}}'
  3.  
    #NF表示读出的行号,加$表示为当前行的内容

  1.  
    #!/bin/bash
  2.  
    awk '{if($0 != "") {print $0}}' ./nowcoder.txt
  3.  
    #NF表示读出的行号,加$表示为当前行的内容

方法3:grep查找

Linux grep 命令用于查找文件里符合条件的字符串。

-E 使用正则表达式
-v 过滤掉符合pattern的行

  1.  
    #!/bin/bash
  2.  
    grep -Ev '^$'

  1.  
    #!/bin/bash
  2.  
    grep -e '\S'

方法4:通过管道可以直接过滤

  1.  
    #!/bin/bash
  2.  
    cat nowcoder.txt | awk NF

NF指只会记录有数据的行

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgebjia
系列文章
更多 icon
同类精品
更多 icon
继续加载