简体   繁体   English

如何打印文件中的第五行

[英]how to print every fifth row in a file

I have a file with numbers 我有一个带数字的文件

20
18
21
16
14
30
40
24

and I need to output four files with rows printed with intervals of 4 So we have rows 1,5,9... 而且我需要输出四个文件,行的打印间隔为4,所以我们有1,5,9行...

20
14

Then rows 2,6,10... 然后第2、6、10行...

18
30

Then 3,7,11... 然后3,7,11 ...

21
40

and then 4,8,12... 然后是4,8,12 ...

16 
24

I did try the code below but it does not give me the control over the starting row 我确实尝试了下面的代码,但没有给我对开始行的控制权

awk 'NR % 4 == 0'

In a single awk you can do: 在一个awk中,您可以执行以下操作:

awk '{print > ("file" (NR%4))}' inputfile

This will send the output to files file0 , file1 , file2 and file3 这会将输出发送到文件file0file1file2file3

You may use these awk commands: 您可以使用以下awk命令:

awk -v n=1 'NR%4 == n%4' file
20
14

awk -v n=2 'NR%4 == n%4' file
18
30

awk -v n=3 'NR%4 == n%4' file
21
40

awk -v n=4 'NR%4 == n%4' file
16
24

IMHO awk is the best solution. 恕我直言awk是最好的解决方案。 You can use sed : 您可以使用sed
Inputfile generated with seq 12 : 使用seq 12生成的输入文件:

for ((i=1;i<5; i++)); do 
   sed -n $i~4w$i.out <(seq 12)
done

Here w$i.out writes to file $i.out. w$i.out在这里写入文件$ i.out。

这可能对您有用(GNU sed):

sed -ne '1~4w file1' -e '2~4w file2' -e '3~4w file3' -e '4~4w file4' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在bash中单词的每五个字符后添加连字符 - How to add a hyphen after every fifth character of a word in bash 如何打印git存储库中每个文件的最后提交信息 - How print last commit info for every file in a git repository 将两列与文件中的一组数字进行比较,并使用UNIX为每一行打印匹配的数字 - Compare two columns with a set of numbers in a file and print matching numbers for every row using unix 如何将SHA哈希列动态添加到CSV文件(每行)? - How to add SHA hash column dynamically to (every row in) CSV file? 在每行文件前打印文件名 - Print name of the file in front of every line of file 我可以通过Unix进行哈希处理吗,在该哈希中,一列中的每一行都打印与其他选项卡文件中另一列相对应的所有重合 - Could I perform a hash by Unix in which for every row in one column print all coincidences corresponding to other column within other tab file 打印文件中的每n行 - Print every n lines from a file 每微秒将每一行打印到文件 - Print each line to file every microsecond 如何使用任何Linux工具在FILENAME之前的每个文件的第n(5)行打印? - How can I print the nth (5th) line of every file preceded by the FILENAME using any linux tool? 打印日志文件第五列时出现awk错误 - awk error while printing the fifth column of log file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM