首页 > 试题广场 >

打印空行的行号

[编程题]打印空行的行号
  • 热度指数:67671 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
编写一个shell脚本以输出一个文本文件nowcoder.txt中空行的行号(空行可能连续,从1开始输出

示例:
假设 nowcoder.txt 内容如下:
a
b

c

d

e


f
你的脚本应当输出:
3
5
7
9
10
示例1

输入

a
b

c

d

e


f

输出

3
5
7
9
10
awk '/^$/ {print NR}'
发表于 2020-12-01 22:29:33 回复(0)
#!/bin/bash
awk '{if($0 == "") {print NR}}' ./nowcoder.txt

编辑于 2020-12-20 14:25:47 回复(2)
sed -n  '/^$/='  "nowcoder.txt"

-n 对匹配的行做处理

=打印匹配到的内容的行号
p打印匹配到的内容
发表于 2020-11-12 21:12:34 回复(2)
1.   grep -n '^$' nowcoder.txt |cut -d ':' -f 1
2.  grep -n '^$' nowcoder.txt | awk -F: '{print $1}'
3. grep -n '^$' nowcoder.txt | sed 's/\:/\ /g'
4. awk  'NF==0{print NR}'  nowcoder.txt
发表于 2021-11-02 19:15:19 回复(0)
awk '/^\s*$/{print NR}' nowcoder.txt
如果空行里面全都是空格或者有tab的话还得需要\s*来过滤一下,如果直接^$的话起不到过滤空格 tab的作用
发表于 2021-05-30 14:25:25 回复(0)
#!/bin/bash
#利用grep查找空行并打印(有冒号),然后用sed把冒号替换成空并打印
grep -n "^ $"  nowcoder.txt | sed -n 's@\:@@p'

发表于 2021-02-25 13:12:00 回复(3)
#!/bain/bash
grep -n "^$"  nowcoder.txt | cut -d ":" -f 1
发表于 2021-01-29 12:17:53 回复(0)
grep 指令用于查找内容包含指定的范本样式的文件
-n : 在显示符合样式的那一行之前,标示出该行的列数编号。
cut 命令从文件的每一行剪切字节、字符和字段并将这些字节、字符和字段写至标准输出。
-d :自定义分隔符,默认为制表符。
-f :与-d一起使用,指定显示哪个区域。
grep -n ^$ nowcoder.txt|cut -d ":" -f 1

发表于 2022-05-23 01:15:13 回复(0)
sed -n '/^$/='
awk '/^$/{print NR}'

发表于 2022-05-09 10:57:59 回复(0)

i=1;while read p; do if [[ $p == '' ]]; then echo $i; fi; ((i++)); done < nowcoder.txt
i=1;while read p; do if [ -z $p ]; then echo $i; fi; ((i++)); done < nowcoder.txt
awk '/^$/ {print NR}' nowcoder.txt
sed -n '/^$/=' nowcoder.txt
grep -n '^$' nowcoder.txt | awk -F: '{print $1}'
grep -n "^$" nowcoder.txt | sed -n 's/\://p'
grep -n "^$" nowcoder.txt | sed 's/\://g'
grep -n "^$" nowcoder.txt | sed "s@:@@g"

发表于 2021-06-02 16:40:33 回复(3)
#!/bin/bash

awk '/^$/{print NR}' nowcoder.txt

发表于 2025-06-06 14:10:52 回复(0)
grep -n '^$' nowcoder.txt | grep -Eo '[0-9]+'

发表于 2025-05-13 09:31:49 回复(0)
for num in {1..10}
do
    if [ -z "$(awk "NR==$num" nowcoder.txt)" ]; then
        echo "$num"
    fi
done

发表于 2025-03-12 16:38:54 回复(0)
1.查看带行号的文件, 获取第二类数据,如果第二列数据为空,打印行号
cat -n nowcoder.txt | awk '$2=="" {print $1}' 
2.当当前行字段数NF为0,则打印行号NR
awk 'NF==0 {print NR}' nowcoder.txt

发表于 2025-03-08 23:24:56 回复(0)
grep -n '^$' nowcoder.txt | cut -d ':' -f 1
发表于 2025-03-04 14:26:54 回复(0)
#!/bin/bash

for i in $(awk '/^\s*$/{print NR}' nowcoder.txt)
do
    echo $i
done

发表于 2024-12-07 22:51:59 回复(0)
grep -n '^$'  文件名
发表于 2024-10-29 16:37:28 回复(0)
grep -n '^$' nowcoder.txt | awk '{print $1}' | sed 's/://g'
发表于 2024-10-13 19:17:12 回复(0)
awk '{if(NF==0){print NR}}' nowcoder.txt
发表于 2024-06-29 20:42:27 回复(0)
cnt=0
cat nowcoder.txt | while read line
do
    cnt=$((cnt+1))
    if [[ "$line" == "" ]]; then
        echo $cnt
    fi
done
发表于 2024-06-21 22:08:37 回复(0)