Eytan Eytan - 5 months ago 16
Bash Question

how to indent the lines in file + bash

I have many files like the following ( the same concept on all the files )

more list-OS23

linux-d
linux-01 fedora-linux-c
Solaris_machine1
AIX-65 linux-redhat18 unixware7-h unix-digital
linux56-a linuxr9


my target is to indent the lines as the following format order

more list-OS23


cycel 1 cycel2 cycel3 cycel4


linux-d fedora-linux-c unixware7-h unix-digital
linux-01 linux-redhat18
Solaris_machine1 linuxr9
AIX-65
linux56-a


I try to indent the file/s by awk

awk '{print $1" "$2" "$3}' file


but the indentation not as I expected

can I get idea or real example how to indent the file?

I think printf is good command for this propose

Answer
$ cat tst.sh
awk '
{
    for (i=1;i<=NF;i++) {
        rowNr = ++rowNrs[i]
        colNr = ++colNrs[rowNr]
        vals[rowNr,colNr] = $i
        numCols = (NF > numCols ? NF : numCols)
    }
}
END {
    for (colNr=1; colNr <= numCols; colNr++) {
        printf "cycle%s%s", colNr, (colNr<numCols ? OFS : ORS)
    }
    for (rowNr=1; rowNr <= NR; rowNr++) {
        for (colNr=1; (rowNr,colNr) in vals; colNr++) {
            printf "%s%s", (colNr>1 ? OFS : ""), vals[rowNr,colNr]
        }
        print ""
    }
}
' "$1" | column -t

$ ./tst.sh file
cycle1            cycle2          cycle3       cycle4
linux-d           fedora-linux-c  unixware7-h  unix-digital
linux-01          linux-redhat18
Solaris_machine1  linuxr9
AIX-65
linux56-a
Comments