基于匹配模式在Unix文件中组合多行

时间:2012-08-07 09:32:49

标签: unix

我有一个文件如下:

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

我必须将这两行合并并获得如下输出:

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

我尝试使用tr并用空格替换换行符,但它不起作用。有人可以帮忙吗。

感谢。

1 个答案:

答案 0 :(得分:1)

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

示例:

$ 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

说明:r;$!{N;br};将所有文件读入模式空间,然后搜索所有看起来像某些空格的行,然后搜索一些字母,并删除前面的换行符和额外的空格。有关详细信息,请参阅此sed reference