![](/img/trans.png)
[英]How to cut the nth line of file by using the value of the nth line from another file?
[英]How to display all the lines from the nth line of a file in unix
我想顯示從第 n 行開始的所有行。 說,打印文件的第三行和所有以下行,直到文件結束。 有命令嗎?
你可以用尾巴
摘自聯機幫助頁:
-n, --lines=K output the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth
例如
tail -n +10 file
輸出從第 10 行開始的文件內容
從第 5 行開始顯示:
awk 'NR>4' file
sed -n '3,$p' file
這只是填充文本,因為 stackoverflow 不喜歡短命令行。
打印,但刪除第 1 到 2 行:
sed '1,2d' filename
您可以像這樣使用awk
:
awk 'BEGIN{n=5}NR<=n{next}1' file
BEGIN{n=5}
- 在文件處理開始之前,將n
設置為要跳過的行數 (5)。NR<=n{next}
- 如果行號小於或等於n
則跳過處理。1
- print
其他所有內容的簡寫。 awk
命令可以通過僅將行打印到NR
記錄號為 3 或更多來執行此操作:
awk 'NR>=3' input_file_name
如果需要,您還可以使用變量將值傳遞給awk
:
awk -v n=3 'NR>=n' input_file_name
(您也可以使用-vn=${num}
來使用環境變量)。
您可以使用許多其他工具來完成相同的工作,其中包括tail
、 sed
和perl
,或者,由於這是一個編程問答站點,只需推出您自己的工具:
#include <stdio.h>
int main (void) {
// Need character and # of newlines to skip.
int ch, newlines = 2;
// Loop until EOF or first lines skipped, exit on EOF.
while ((ch = getchar()) != EOF)
if ((ch == '\n') && (--newlines == 0))
break;
if (ch == EOF)
return 0;
// Now just echo all other characters, then return.
while ((ch = getchar()) != EOF)
putchar (ch);
return 0;
}
現在您通常不會為此編寫自己的過濾器程序,但是,由於您要求最短的命令,您可以使用該源代碼創建一個名為x
的可執行文件來執行此操作:
x <input_file_name
你很難找到比這更短的命令。 當然,假設您在 UNIXy 環境中(特別是bash
),您也可以:
alias x awk 'NR>=3'
:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.