[Linux] 輸出文件的指定行

1.獲取第k行(以k=10爲例)web

要注意的是,若是文件包含內容不足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行:spa

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

 

題目來自Leetcode的195. Tenth Linecode

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

 

2.獲取某些行ip

sed '/pattern/!p' file.txt   //匹配pattern的行不輸出 
sed -n '5,9p' file.txt        //輸出第五和第九行
sed -n '10,$p' file.txt      //輸出第十行到最後一行
相關文章
相關標籤/搜索