user4737714
user4737714

Reputation:

SED. How to append a previous string to a current?

I have a file with following strings:

1.44 1.12 
disk 1.00 0.15 0.21
1.15 1.08
disk2 0.15 0.13 0.11

How to append 1 string to 2. Not 2 to 1. To get like this:

disk 1.00 0.15 0.21 1.44 1.12
disk2 0.15 0.13 0.11 1.15 1.08

For example with sed?

Upvotes: 0

Views: 55

Answers (3)

Jotne
Jotne

Reputation: 41450

Here is another awk version if all lines needed starts with data:

awk '/^disk/ {print $0,p} {p=$0}' file
disk 1.00 0.15 0.21 1.44 1.12
disk2 0.15 0.13 0.11 1.15 1.08

Some golfing:

awk '/^disk/&&$0=$0p; {p=$0}' file
disk 1.00 0.15 0.211.44 1.12
disk2 0.15 0.13 0.111.15 1.08

Upvotes: 1

Wintermute
Wintermute

Reputation: 44043

With sed:

sed -n 'h;n;G;s/\n/ /;p' file

This will

h        # save the line in the hold buffer
n        # fetch the next line to the pattern space
G        # append the hold buffer to the pattern space
s/\n/ /  # replace the newline between them with a space
p        # and print the result.

Upvotes: 3

fedorqui
fedorqui

Reputation: 289855

If you want to join two consecutive lines, you can for example say this in awk:

$ awk 'NR%2 {prev=$0; next} {print $0, prev}' file
disk 1.00 0.15 0.21 1.44 1.12 
disk2 0.15 0.13 0.11 1.15 1.08

This stores the odd lines in a variable prev and prints it later on together with the even line.

Upvotes: 2

Related Questions