AWK从文件中每第n行打印一次 [英] AWK to print every nth line from a file

查看:891
本文介绍了AWK从文件中每第n行打印一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用AWK打印文件的每N行. 我试图修改通用格式:-

i want to print every Nth line of a file using AWK. i tried modifying the general format :-

awk '0 == NR % 4' results.txt

至:-

awk '0 == NR % $ct' results.txt

其中"ct"是应跳过的行数. 它不起作用.有人可以帮我吗? 预先感谢.

where 'ct' is the number of lines that should be skipped. its not working . can anyone please help me out? Thanks in advance.

推荐答案

您可能要使用:

awk -v patt="$ct" 'NR % patt' results.txt

说明

给出如下文件:

Explanation

Given a file like the following:

$ cat -n a
     1  hello1
     2  hello2
     3  hello3
     4  hello4
     5  hello5
     ...
    37  hello37
    38  hello38
    39  hello39
    40  hello40

这些是等效的:

$ awk 'NR % 7 == 0' a
hello7
hello14
hello21
hello28
hello35
$ ct=7
$ awk -v patt="$ct" 'NR % patt == 0' a
hello7
hello14
hello21
hello28
hello35

甚至

$ awk -v patt="$ct" '!(NR % patt)' a

请注意,语法NR % n == 0表示:行数是n的倍数.如果我们说!(NR % patt),那么只要NR % patt为假,即NRpatt的倍数,就为true.

Note that the syntax NR % n == 0 means: number of line is multiple to n. If we say !(NR % patt), then this is true whenever NR % patt is false, ie, NR is multiple of patt.

在评论时,您使用的是Solaris,而不是默认的awk,请使用以下内容:

As you comment you are using Solaris, instead of default awk use the following:

/usr/xpg4/bin/awk

这篇关于AWK从文件中每第n行打印一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆