首页 > 试题广场 >

去掉空行

[编程题]去掉空行
  • 热度指数:46281 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
写一个 bash脚本以去掉一个文本文件nowcoder.txt中的空行
示例:
假设nowcoder.txt 内容如下:
abc

567


aaa
bbb



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

输入

abc

567


aaa
bbb



ccc

输出

abc
567
aaa
bbb
ccc
#!/bin/bash

awk '/./{print}' nowcoder.txt

发表于 2025-06-06 14:15:13 回复(0)
grep -Ev '^$' nowcoder.txt

发表于 2025-05-13 09:33:18 回复(0)
#!/bin/bash
awk '/./' nowcoder.txt
这样提交也对了 不知道有没有错
发表于 2025-04-30 18:16:09 回复(0)
#!/bin/bash

IFS=$'\n'
for i in $(cat nowcoder.txt)
do
    echo $i
done
 改变分隔符,通过循环读取也能做到,就是稍微麻烦
编辑于 2023-12-04 01:30:17 回复(0)
# 方法一、
# sed -n '/^$/!p' nowcoder.txt提交观点

# 方法二、
# cat nowcoder.txt |grep -v "^$"

# 方法三、
awk '!/^$/{print }' nowcoder.txt
发表于 2023-09-22 15:16:12 回复(0)
我建议把题目改成输出文件除空行外的内容。
按照本题的意思本来应该用sed -i '/^$/d' nowcoder.txt
但实际上用 grep -v "^$" nowcoder.txt  才能通过题目


发表于 2023-07-12 21:28:04 回复(1)
grep -v '^$' 
awk '!/^$/'
sed -n '/[^$]/p'
sed '/^$/d'

发表于 2023-02-09 11:52:10 回复(0)
awk '$1 ~ /^\S+$/ {print $1}' nowcoder.txt
这个能通过,但是我在ubuntu上执行没有效果。

ubuntu上能执行成功的是:
awk '$1 !~ /^\S*$/ {print $1}' nowcoder.txt
但在牛客上无法通过。

怀疑是编码的问题,但是不太好验证。
发表于 2022-09-12 20:38:27 回复(0)
sed '/^$/d' nowcoder.txt
awk -v RS='\n+' '{print $0}' nowcoder.txt
发表于 2022-08-27 17:20:14 回复(0)
cat nowcoder.txt|grep -v '^$'
发表于 2022-08-03 17:19:32 回复(0)
grep -v '^$' nowcoder.txt
发表于 2022-07-25 23:06:48 回复(0)
#!/bin/bash
grep "^[^\s]" nowcoder.txt
发表于 2022-07-11 23:25:09 回复(0)
awk '!/^\s*$/ {print $NF}' nowcoder.txt
发表于 2022-06-21 22:25:56 回复(0)
sed -n '/^[^$]/p' nowcoder.txt

对空行取反匹配
发表于 2022-06-06 17:56:30 回复(0)
line=1
while read value
do 
    # 检测字符串是否为空,不为空返回 true。
    if [ $value  ]
    then 
          echo $value;
    fi
        line=$((line+1));
done < nowcoder.txt
发表于 2022-05-19 10:25:26 回复(0)
sed -n '/^$/!p' nowcoder.txt 


发表于 2022-05-18 14:32:57 回复(0)
sed '/^$/d'
awk '!/^$/{print}'


发表于 2022-05-09 11:36:43 回复(0)