Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

regex - How to switch/rotate every two lines with sed/awk?

I have been doing this by hand and I just can't do it anymore-- I have thousands of lines and I think this is a job for sed or awk.

Essentially, we have a file like this:

A sentence X
A matching sentence Y
A sentence Z
A matching sentence N

This pattern continues for the entire file. I want to flip every sentence and matching sentence so the entire file will end up like:

A matching sentence Y
A sentence X
A matching sentence N
A sentence Z

Any tips?

edit: extending the initial problem

Dimitre Radoulov provided a great answer for the initial problem. This is an extension of the main problem-- some more details:

Let's say we have an organized file (due to the sed line Dimitre gave, the file is organized). However, now I want to organize the file alphabetically but only using the language (English) of the second line.

watashi 
me
annyonghaseyo
hello
dobroye utro!
Good morning!

I would like to organize alphabetically via the English sentences (every 2nd sentence). Given the above input, this should be the output:

dobroye utro!
Good morning!
annyonghaseyo
hello
watashi
me 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the first part of the question, here is a one way to swap every other line with each other in sed without using regular expressions:

sed -n 'h;n;p;g;p'

The -n command line suppresses the automatic printing. Command h puts copies the current line from the pattern space to the hold space, n reads in the next line to the pattern space and p prints it; g copies the first line from the hold space back to the pattern space, bringing the first line back into the pattern space, and p prints it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...