简体   繁体   中英

Bash print columns with varying number of values

I'm attempting to create a report that breaks down the different dependency files from an original source file, then output that in a report with columns. Thus far, I can get the file lists to generate, but the fourth column is the only column with multiple values and this is what I get:

file='foo.rcf'
gen_file='foo2.rcf'
fs_file='foo3.rcf'
item_file='foo4.rcf
foo5.rcf
foo6.rcf
foo7.rcf'

paste <(printf %s "$file |") <(printf %s "$fs_file |") <(printf %s "$gen_file |") <(printf "%10s\n""$item_file")

Output:

foo.rcf |       foo3.rcf |      foo2.rcf |      foo4.rcf
                        foo5.rcf
                        foo6.rcf
                        foo7.rcf

What I'm hoping to be able to output is something along these lines:

foo.rcf |       foo3.rcf |      foo2.rcf |      foo4.rcf
        |                |               |      foo5.rcf
        |                |               |      foo6.rcf
        |                |               |      foo7.rcf

A bash solution would be awesome, but I'm really looking for any solution at this point.

Use column . First with paste join the lines using some separator and then columnize the output with column with fields separated by that separator:

file='foo.rcf'
gen_file='foo2.rcf'
fs_file='foo3.rcf'
item_file='foo4.rcf
foo5.rcf
foo6.rcf
foo7.rcf'

paste -d'|' <(
    printf %s "$file") <(
    printf %s "$fs_file") <(
    printf %s "$gen_file") <(
    printf %s "$item_file") |
column -t -s '|' -o ' |     '

would output:

foo.rcf |     foo3.rcf |     foo2.rcf |     foo4.rcf
        |              |              |     foo5.rcf
        |              |              |     foo6.rcf
        |              |              |     foo7.rcf

You can use awk:

file='foo.rcf'
gen_file='foo2.rcf'
fs_file='foo3.rcf'
item_file='foo4.rcf
foo5.rcf
foo6.rcf
foo7.rcf'

# Lets concatenate the string with separators:
printf "$file|$fs_file|$gen_file|$item_file" |
# Sending modified string to awk with pipe---^
# awk can split it with -F parameter and insert tabs between the chunks.
awk -F'|' 'NR==1 {
    print $1"\t\t|\t"$2"\t|\t"$3"\t|\t"$4
} NR>1 { 
    print "\t\t|\t\t\t|\t\t\t|\t"$1  }'
# -F defines a separator, NR is line number.

Output:

foo.rcf     |   foo3.rcf    |   foo2.rcf    |   foo4.rcf
            |               |               |   foo5.rcf
            |               |               |   foo6.rcf
            |               |               |   foo7.rcf

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