使用sed删除每n行的换行符 [英] Remove line break every nth line using sed

查看:642
本文介绍了使用sed删除每n行的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:是否有一种方法可以使用sed为每3n + 1和3n + 2行删除/替换文件中的模式?

Example: Is there a way to use sed to remove/subsitute a pattern in a file for every 3n + 1 and 3n+ 2 line?

例如,转动

Line 1n/
Line 2n/
Line 3n/
Line 4n/
Line 5n/
Line 6n/
Line 7n/
...

收件人

Line 1 Line 2 Line 3n/
Line 4 Line 5 Line 6n/
...

我知道awk可以解决这个问题.但是sed呢?

I know this can probably be handled by awk. But what about sed?

推荐答案

好吧,我只用awk来表示 1 ,因为它有点复杂,但是,如果您确实为了使用sed,下面的命令会将三行的组合并为一行(尽管换行符使用/n的情况很奇怪,但根据标题和文本,这似乎是您要执行的操作):

Well, I'd just use awk for that1 since it's a little more complex but, if you're really intent on using sed, the following command will combine groups of three lines into a single line (which appears to be what you're after based on the title and text, despite the strange use of /n for newline):

sed '$!N;$!N;s/\n/ /g'

有关如何对此进行测试,请参见以下文字记录:

See the following transcript for how to test this:

$ printf 'Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n' | sed '$!N;$!N;s/\n/ /g'
Line 1 Line 2 Line 3
Line 4 Line 5

子命令如下:

  • $!N会将下一行追加到模式空间,但是仅当您不在最后一行时(您执行两次以得到三行).模式空间中的每一行都由换行符分隔.
  • s/\n/ /g用空格字符替换模式空间中的所有换行符,从而有效地将三行合并为一个.
  • $!N will append the next line to the pattern space, but only if you're not on the last line (you do this twice to get three lines). Each line in the pattern space is separated by a newline character.
  • s/\n/ /g replaces all the newlines in the pattern space with a space character, effectively combining the three lines into one.

1 类似于:

awk '{if(NR%3==1){s="";if(NR>1){print ""}};printf s"%s", $0;s=" "}'

这很复杂,因为您可能不想在每行的末尾使用多余的空格,因此必须引入s变量.

This is complicated by the likelihood you don't want an extraneous space at the end of each line, necessitating the introduction of the s variable.

由于sed变体较小(一旦您理解它,它就不会那么复杂),因此最好还是坚持使用它.好吧,至少到您想要组合17行的组,或者做其他比sed还要复杂的事情:-)

Since the sed variant is smaller (and less complex once you understand it), you're probably better off sticking with it. Well, at least up to the point where you want to combine groups of 17 lines, or do something else more complex than sed was meant to handle :-)

这篇关于使用sed删除每n行的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆