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

567


aaa
bbb

ccc

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

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

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

#!/bin/bash
while read line
doif [[ -z $line ]] then# 删除空行continuefiecho $line
done < nowcoder.txt

#!/bin/bash
while read line
doif [[ $line == '' ]] then# 删除空行continuefiecho $line
done < nowcoder.txt

#!/bin/bash
while read line
doif [[ $line != '' ]] then# 删除空行echo $linefi
done < nowcoder.txt

方法2:awk实现

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

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

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

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

或管道

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

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

方法3:grep查找

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

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

#!/bin/bash
grep -Ev '^$'

#!/bin/bash
grep -e '\S'

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

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

NF指只会记录有数据的行