简体   繁体   中英

unix shell scripting to merge multiple lines

I have one text file. The content:

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

the output I want is like:

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

One solution using 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

You can change the value of n to match the block size of the input.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM