print output to 3 separate columns

  • MYPATH=/var/www/html/error_logs/
    TOTALFILE=$(ls $MYPATH* | wc -l)
    FILETIME=$(stat --format=%y $MYPATH* | head -5 | cut -d'.' -f1)  
    FILE=$(ls -1tcr $MYPATH* | head -5 | rev | cut -d/ -f1 | rev)
    TOPLINE=$(head -1 $MYPATH* | grep -Po '".*?"' | head -5)
    

    how can i elegantly print this out 5 files information into columns with headers?

    FILE CREATED TIME   | FILE NAME        | ERROR HEADER
    ---------------------------------------------
    $FILETIME           | $FILE            | $TOPLINE
    2012-11-29 11:27:45 | 684939947465     | "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"
    

    and so on 5 files

    total files: $TOTALFILE

    is there any easy way to get what i want?

    note: this output i got when echo every variable

    2012-11-29 11:27:45 2012-11-29 11:27:41 2012-11-28 23:33:01 2012-11-26 10:23:37 2012-11-19 22:49:36
    684939947465 1313307654813 1311411049509 1234980770182 354797376843
    "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)" "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)" "Connection to localhost:6379 failed: Connection refused (111)" "An error occurred connecting to Redis." "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"
    

    You got three answers to your question, which all address the things you ask. You should be much more precise in what you want to get a specific answer.

  • QNimbus

    QNimbus Correct answer

    8 years ago

    You can use the shell command 'column' for that, check: column MAN page.

    Combine this with a loop and you're in business, e.g.:

    #!/bin/sh
    
    MYPATH=/
    TOTALFILE=$(ls $MYPATH/* | wc -l)
    FILE=$(ls -1tcr $MYPATH/* | head -5 | rev | cut -d/ -f1 | rev)
    
    declare -a FILES
    declare -a FILETIME
    
    OUTPUT="FILENAME CREATED TIME ERROR_HEADER\n\n------------------------------ ----------------------------- ----------------------------------- ------$
    
    for i in $MYPATH/*;
    do
        FILES[${#FILES[@]}]="$i"
        FILETIME[${#FILETIME[@]}]=$(stat --format=%y $i | head -5 | cut -d'.' -f1)
        TOPLINE=$(head -1 $i | grep -Po '".*?"' | head -5)
    
        OUTPUT="$OUTPUT\n${FILES[${#FILES[@]}-1]} ${FILETIME[${#FILETIME[@]}-1]} $TOPLINE\n"
    done
    
    echo -ne $OUTPUT | column -t
    

    I needed further control of what went in which column, so I split columns on '*' and used something like `sed 's/^/ \* \*/g'` for shifting things from first column into third. Worked a treat for me.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM