ahb65
ahb65

Reputation: 191

bash- remove \n every three lines

How can I remove newline delimiter from every three lines. Example:

input:

1
name
John
2
family 
Grady
3
Tel
123456

output:

1
name John
2
family Grady
3
Tel 123456

Upvotes: 1

Views: 3080

Answers (7)

confused00
confused00

Reputation: 2612

Unix way:

$ paste -sd'\n \n' input

Output:

1
name John
2
family Grady
3
Tel 123456

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882146

Assuming all those lines you want joined with the next one end with : (your original question):

1
name:
John
2
family: Grady
3
Tel:
123456

You can use sed for this, with:

sed ':a;/:$/{N;s/\n//;ba}'

The a is a branch label. The pattern :$ (colon at end of line) is detected and, if found, N appends the next line to the current one, the newline between them is removed with the s/\n// substitution command, and it branches back to label a with the ba command.


For your edited question where you just want to combine the second and third line of each three-line group regardless of content:

1
name
John
2
family 
Grady
3
Tel
123456

Use:

sed '{n;N;s/\n/ /}'

In that command sequence, n will output the first line in the group and replace it with the second one. Then N will append the third line to that second one and s/\n/ / will change the newline between them into a space before finally outputting the combined two-three line.

Then it goes onto the next group of three and does the same thing.


Both those commands will generate the desired output for their respective inputs.

Upvotes: 2

potong
potong

Reputation: 58488

This might work for you (GNU sed):

sed 'n;N;s/\n//' file

to replace the newline with a space use:

sed 'n:N;s/\n/ /' file

as an alternative use paste:

paste -sd'\n \n' file

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174796

You could do this in Perl,

$ perl -pe 's/\n/ /g if $. % 3 == 2' file
1
name John
2
family Grady
3
Tel 123456

Upvotes: 2

a5hk
a5hk

Reputation: 7844

awk 'NR%3==2{printf "%s ",$0;next}{print $0}' input.txt

Output:

1
name John
2
family Grady
3
Tel 123456

Upvotes: 2

Steve
Steve

Reputation: 54532

One way using AWK:

awk '{ printf "%s%s", $0, (NR%3==2 ? FS : RS) }' file

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249464

Yet another solution, in Bash:

while read line
do
  if [[ $line = *: ]]
  then
    echo -n $line
  else
    echo $line
  fi
done < input.txt

Upvotes: 0

Related Questions