簡體   English   中英

從文本文件中刪除奇數或偶數行

[英]Remove odd or even lines from a text file

我需要刪除文本文件中的奇數行以進行下采樣。 我找到了這個命令,

awk 'NR%2==0' file

但它只在終端中打印奇數行。 如何真正去除它們?

我真的不關心偶數或奇數,我希望它們從文件中刪除或打印在另一個文件中。 這只會在終端中打印它們。

awk

%是模數運算符, NR是當前行號,因此NR%2==0僅對偶數行為真,並將為它們調用默認規則( { print $0 } )。 因此,只保存偶數行,將輸出從awk重定向到一個新文件:

awk 'NR%2==0' infile > outfile

sed

你可以用sed完成同樣的事情。 devnulls答案顯示了如何使用GNU sed做到這一點。 以下是沒有~運算符的sed版本的替代方案:

保持奇數行

sed 'n; d' infile > outfile

保持均勻的線條

sed '1d; n; d' infile > outfile

使用 GNU sed:

sed -i '0~2d' filename

從文件中刪除偶數行。

刪除奇數行:

sed -i '1~2d' filename

-i選項會導致將更改就地保存到文件中。

引用手冊:

`FIRST~STEP'
     This GNU extension matches every STEPth line starting with line
     FIRST.  In particular, lines will be selected when there exists a
     non-negative N such that the current line-number equals FIRST + (N
     * STEP).  Thus, to select the odd-numbered lines, one would use
     `1~2'; to pick every third line starting with the second, `2~3'
     would be used; to pick every fifth line starting with the tenth,
     use `10~5'; and `50~0' is just an obscure way of saying `50'.

這可能對您有用(GNU 和非 GNU sed):

 sed -n 'p;n' file # keep odd
 sed -n 'n;p' file # keep even

-n : 禁止打印

p : 打印當前行

n : 下一行

不要關注負面(刪除線條),專注於正面(選擇線條),您的解決方案將效仿。 因此,您應該認為I need to select even lines而不是I need to remove odd lines I need to select even lines ,然后解決方案很簡單:

awk '!(NR%2)' file

如果要將結果保存到新文件:

awk '!(NR%2)' file > newfile

或回到原來的:

awk '!(NR%2)' file > newfile && mv newfile file

這是一個awk示例,用於創建分別包含奇數行和偶數行的兩個新文件:

awk '{ if (NR%2) print > "odd.txt"; else print > "even.txt" }' input.txt

用於將事件打印到新文件的 Perl 解決方案:

perl -lne 'print if $. % 2 == 0' infile > outfile

要打印賠率, == 1更改為== 0

$. 是行號

在原始文件中只保留偶數:

perl -i -lne 'print if $. % 2 == 0' infile

與上面相同,但創建一個名為 infile.bak 的備份文件:

perl -i.bak -lne 'print if $. % 2 == 0' infile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM