LEo
LEo

Reputation: 487

align lines when pasting files in bash

How to align the rows (and use alphabetic sort) when pasting files into columns?

Example:

$ paste <(printf '%s\n' bike car lane road wheel) <(printf '%s\n' car rollers wheel) <(printf '%s\n' bike lane tire wheel) | column -s $'\t' -t
bike   car      bike
car    rollers  lane
lane   wheel    tire
road            wheel
wheel

and the desired output is:

bike            bike
car     car      
lane            lane
road             
        rollers  
                tire
wheel   wheel   wheel

Upvotes: 1

Views: 97

Answers (3)

LEo
LEo

Reputation: 487

Here is an adaptation of @fravadona's answer using array of array and putting it in an awk script.

#!/usr/bin/awk -f

BEGIN {OFS="\t"}
FNR == 1 { ++FILENUM }
{ arr[$0][FILENUM] = $0 }
END {
    for (ln in arr)
         for (i = 1; i <= FILENUM; i++)
             printf ( "%s%s", \
                 (length(arr[ln][i]) > 0 ? arr[ln][i] : "-"), \
                 (i < FILENUM ? OFS : ORS) \
             )
}

Execution example:

./myscript.awk <(printf '%s\n' bike car lane road wheel) \
               <(printf '%s\n' car rollers wheel) \
               <(printf '%s\n' bike lane tire wheel) 
lane    -       lane
bike    -       bike
-       -       tire
wheel   wheel   wheel
car     car     -
-       rollers -
road    -       -

Upvotes: 0

Fravadona
Fravadona

Reputation: 16980

Is that what your looking for?

#!/bin/bash

awk -v OFS='\t' '
    FNR == 1 { ++FILENUM }
    { arr[$0] = arr[$0] FS FILENUM }
    END {
        for (key in arr)
            for (i = 1; i <= FILENUM; i++)
                printf( "%s%s", \
                    (index(arr[key]" ", " "i" ") ? key : "-" ), \
                    (i < FILENUM ? OFS : ORS) \
                )
    }
' <(printf '%s\n' bike car lane road wheel) \
  <(printf '%s\n' car rollers wheel) \
  <(printf '%s\n' bike lane tire wheel)
lane    -   lane
bike    -   bike
-   -   tire
wheel   wheel   wheel
car car -
-   rollers -
road    -   -

Upvotes: 1

DMyers205
DMyers205

Reputation: 1

To align the rows

$ paste file1 file2 | column -t

If you want to make the output easier to read, you can also specify the delimiter to use when pasting. Like a comma or tab.

$ paste -d '\t' file1 file2 | column -t

Upvotes: 0

Related Questions