题注:本文来自某论坛上的提问。
先假设文本的内容是:
In Xanadu did Kubla Khan
A stately pleasure dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
一看到这样的题目就头疼,因为sed学了很久,还是没什么感觉,先说说Vim下的解法吧:
:%s/\n.*\n/\r/g
本人用的gvim win32所以。后面被替换成\r。gaw的解法:
gawk "NR%2" 11.txt
NR是记录的是已读的记录数。不得不佩服awk的作者,这么简单的命令!下面的是sed的解法:
sed "n;d" 1.txt
试着解释一下吧:
n
If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed
exits without processing any more commands.
d
Delete the pattern space; immediately start next cycle.
n命令读取偶数行时并存入到pattern space,d命令就清空pattern space的内容。所以命令输出奇数行。文章开头的文本的读取过程如下:
读取第一行输出;n命令读取第二行,d命令清空pattern space;由于第二行已经读取,所以继续读取第三行,输出;n命令读取第四行,d命令删除pattern space的内容;读取第五行,输出。输出的内容:
In Xanadu did Kubla Khan
Where Alph, the sacred river, ran
Down to a sunless sea.