unix shell脚本来合并多行

时间:2014-11-30 22:25:14

标签: linux bash shell unix awk

我有一个文本文件。内容:

game1
game2
game3
game4
/usr/local/games
/usr/local/games
/usr/local/games
/usr/local/games
10
20
30
40

我想要的输出就像:

game1   /usr/local/games     10
game2   /usr/local/games     20
game3   /usr/local/games     30
game4   /usr/local/games     40

2 个答案:

答案 0 :(得分:2)

使用awk的一个解决方案:

$ awk '{i=(NR-1)%n;a[i]=a[i](a[i]?"\t"$0:$0)}END{for(j=0;j<n;j++)print a[j]}' n=4 file
game1   /usr/local/games        10
game2   /usr/local/games        20
game3   /usr/local/games        30
game4   /usr/local/games        40

您可以更改n的值以匹配输入的块大小。

答案 1 :(得分:0)

awk '
BEGIN { numRows = 4 }
{
    rowNr = (NR-1)%numRows+1
    colNr = ++colCnt[rowNr]
    numCols = (colCnt[rowNr] > numCols ? colCnt[rowNr] : numCols)
    val[rowNr,colNr] = $0
}
END {
    for (rowNr=1; rowNr<=numRows; rowNr++)
        for (colNr=1; colNr<=numCols; colNr++)
            printf "%s%s", val[rowNr,colNr], (colNr < numCols ? OFS : ORS)
}
' file
game1 /usr/local/games 10
game2 /usr/local/games 20
game3 /usr/local/games 30
game4 /usr/local/games 40