bymo

1.获取第k行(以k=10为例)

要注意的是,如果文件包含内容不足10行,应该不输出.

# Read from the file file.txt and output the tenth line to stdout.
# 解法一,使用awk
awk \'NR == 10\' file.txt

# 解法二,使用sed(个人测试结果:sed方法比awk快)
sed -n \'10p\' file.txt

# 解法三,组合使用tail与head
tail -n+10 file.txt | head -n1

# 另外,以下这种方法不符合要求
head file.txt -n10 | tail -n1 # 因为如果文件包含内容不足10行,会输出最后一行

 

另外,输出第5行到第8行:

awk \'NR>=5 && NR <=8\' file.txt

 

题目来自Leetcode的195. Tenth Line

解法参考:http://bookshadow.com/weblog/2015/03/28/leetcode-tenth-line/

 

2.获取某些行

sed \'/pattern/!p\' file.txt   //匹配pattern的行不输出 
sed -n \'5,9p\' file.txt        //输出第五和第九行
sed -n \'10,$p\' file.txt      //输出第十行到最后一行

 

分类:

技术点:

相关文章:

  • 2021-11-21
  • 2021-11-21
  • 2021-07-28
  • 2021-10-03
  • 2021-11-11
  • 2021-11-21
  • 2021-07-12
  • 2021-09-17
猜你喜欢
  • 2021-11-27
  • 2021-09-15
  • 2021-11-27
  • 2021-10-08
  • 2021-09-21
  • 2021-10-16
  • 2021-11-11
相关资源
相似解决方案