visakh
visakh

Reputation: 2553

Combining multiple lines in a Unix file based on a matching pattern

I have a file as follows:

Country:  USA
Currency: Dollars
Country:  Canada
Currency: Canadian
          Dollars
Country:  Australia
Currency: Australian
          Dollars
Country:  France
Currency: Euro

I have to combine the two lines and get output as follows:

Country:  USA
Currency: Dollars
Country:  Canada
Currency: Canadian Dollars
Country:  Australia
Currency: Australian Dollars
Country:  France
Currency: Euro

I tried using tr and replacing the newline with spaces, but it didn't work. Can someone help with this.

Thanks.

Upvotes: 1

Views: 296

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65811

sed ':r;$!{N;br};s/\n[[:space:]]*\([[:alpha:]]\+\n\)/ \1/g' filename

Example:

$ echo 'Country:  USA
> Currency: Dollars
> Country:  Canada
> Currency: Canadian
>           Dollars
> Country:  Australia
> Currency: Australian
>           Dollars
> Country:  France
> Currency: Euro' | sed ':r;$!{N;br};s/\n[[:space:]]*\([[:alpha:]]\+\n\)/ \1/g'
Country:  USA
Currency: Dollars
Country:  Canada
Currency: Canadian Dollars
Country:  Australia
Currency: Australian Dollars
Country:  France
Currency: Euro

Explanation: r;$!{N;br}; reads all file into pattern space, then all lines that look like some spaces followed some letters are searched for and the preceding newlines and extra spaces are removed. See this sed reference for more info.

Upvotes: 1

Related Questions