如何切换/每两行与旋转SED / AWK? [英] How to switch/rotate every two lines with sed/awk?
问题描述
我一直用手工做这个,我只是不能做到这一点anymore--我有成千上万行,我觉得这是awk或者sed的工作。
从本质上讲,我们有这样的文件:
A句点¯x
的匹配句ÿ
一个句子ž
的匹配句ñ
此模式继续用于整个文件。我想翻转每一句话和匹配句话让整个文件最终会像:
A匹配句ÿ
一句话点¯x
的匹配句ñ
一个句子ž
任何提示吗?
编辑:延长了最初的问题
Dimitre Radoulov提供了最初的问题有很大的答案。这是主要的一个扩展problem--一些更多的细节:
让我们说我们有一个有组织的文件(由于sed的行Dimitre了,文件组织)。不过,现在我想组织文件按字母顺序,但只能使用第二行的语言(英语)。
渡
我
annyonghaseyo
你好
dobroye utro!
早上好!
我想通过英语句子(每2句),按字母顺序组织。鉴于上述输入,这应该是输出:
dobroye utro!
早上好!
annyonghaseyo
你好
渡
我
ñsed的';
S / \\(。* \\)\\ n \\(。* \\)/ \\ 2 \\
\\ 1 /'的infile
N
- 输入的下一行追加到模式空间结果 \\(。* \\)\\ n \\
(* \\。) - 保存模式空间的匹配部分
一个前后换行后的人。结果 \\ 2 \\\\
- 交换两行(\\ 1是第一个保存的部分,
\\ 1
\\ 2秒)。使用逃脱面值换行符的便携性。
对于一些SED实现你可以使用转义序列
\\ N: \\ 2 \\ n \\ 1
而不是
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
sed 'N;
s/\(.*\)\n\(.*\)/\2\
\1/' infile
N
- append the next line of input into the pattern space
\(.*\)\n\(.*\)
- save the matching parts of the pattern space
the one before and the one after the newline.
\2\\
\1
- exchange the two lines (\1 is the first saved part,
\2 the second). Use escaped literal newline for portability
With some sed implementations you could use the escape sequence
\n: \2\n\1
instead.
这篇关于如何切换/每两行与旋转SED / AWK?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!