【Leetcode Shell】Tenth Line

本文介绍如何在Linux环境中仅显示文本文件的第10行内容。通过使用不同的命令行工具如awk、sed以及组合使用tail和head,展示了多种实用的方法。这些技巧对于日常的文本处理工作非常有用。

题目:

How would you print just the 10th line of a file?

For example, assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Your script should output the tenth line, which is:
Line 10
1
2
3
4
5
6
7
8
9
10
11
12
13
# Read from the file words.txt and output the word frequency list to stdout.
#!/bin/bash
#其中反引号的作用就是将反引号内的Linux命令先执行,然后将执行结果赋予变量。
#先用wc -l命令找到file.txt文件共有多少行,其中有两个字段第一个是行数,第二个是文件名。
#通过awk命令找出第一个字段$1,将行数赋给rownum
rownum=`wc -l file.txt | awk '{print $1}'`
#如果行数小于10,则返回空字符串
if $rownum -lt 10 ]; then
    echo ""
#如果行数大于等于10,则通过sed命令先删除前9行,然后通过head命令打印出剩下的第一行
else
    sed '1,9d' file.txt | head -1
fi

注意:sed '1,9d' file.txt | head -1  
      这一行代码中的'1,9d'是指删除1到9行,输出剩余内容。但是不会真的删除file.txt中的内容。
不过在网上发现几个非常好的方法,算是学习了
1、用awk方法
1
awk 'NR == 10' file.txt
2、使用sed
1
sed -n '10p' file.txt
3、组合使用tail与head
1
tail -n +10 file.txt | head -n 1
学无止境啊,加油

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值