Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove line break every nth line using sed

Tags:

linux

bash

sed

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

For example, turn

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

To

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

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

like image 671
user3805884 Avatar asked Jan 07 '23 18:01

user3805884


1 Answers

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

The sub-commands are as follows:

  • $!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 With something like:

awk '{if(NR%3==1){s="";if(NR>1){print ""}};printf s"%s", $0;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.

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 :-)

like image 174
paxdiablo Avatar answered Jan 15 '23 01:01

paxdiablo