用awk实现head、tail和tac

文件名称:actress_rankings.txt
文件内容:

1 Keira Knightley
2 Natalie Portman
3 Monica Bellucci
4 Bonnie Hunt
5 Cameron Diaz
6 Annie Potts
7 Liv Tyler
8 Julie Andrews
9 Lindsay Lohan
10 Catherine Zeta-Jones
11 CateBlanchett
12 Sarah Michelle Gellar
13 Carrie Fisher
14 Shannon Elizabeth
15 Julia Roberts
16 Sally Field
17 TeaLeoni
18 Kirsten Dunst
19 Rene Russo
20 JadaPinkett

 

模拟head打印文件前10行
[root@zhangshibo temp]# awk 'NR<=10' actress_rankings.txt
1 Keira Knightley
2 Natalie Portman
3 Monica Bellucci
4 Bonnie Hunt
5 Cameron Diaz
6 Annie Potts
7 Liv Tyler
8 Julie Andrews
9 Lindsay Lohan
10 Catherine Zeta-Jones

模拟tail命令打印文件后10行
[root@zhangshibo temp]# awk '{ buffer[NR % 10] = $0; } END { for(i=1;i<11;i++){print buffer[i%10]}}' actress_rankings.txt
11 CateBlanchett
12 Sarah Michelle Gellar
13 Carrie Fisher
14 Shannon Elizabeth
15 Julia Roberts
16 Sally Field
17 TeaLeoni
18 Kirsten Dunst
19 Rene Russo
20 JadaPinkett

 

模拟tac命令逆序打印输入文件所有行
[root@zhangshibo temp]# awk '{ buffer[NR] = $0; } END { for(i=NR;i>0;i--){print buffer[i]}}' actress_rankings.txt
20 JadaPinkett
19 Rene Russo
18 Kirsten Dunst
17 TeaLeoni
16 Sally Field
15 Julia Roberts
14 Shannon Elizabeth
13 Carrie Fisher
12 Sarah Michelle Gellar
11 CateBlanchett
10 Catherine Zeta-Jones
9 Lindsay Lohan
8 Julie Andrews
7 Liv Tyler
6 Annie Potts
5 Cameron Diaz
4 Bonnie Hunt
3 Monica Bellucci
2 Natalie Portman
1 Keira Knightley


[root@zhangshibo temp]#

你可能感兴趣的:(用awk实现head、tail和tac)