Question

This code is to display the content of str1 in columns:

str1='Name: Robert Jhonson  21
Name: Flex Maxed 23
Name: Thisisaverylongname         andlongsurname 44'

IFS=$'\n'

echo "$str1" | column -t

Return this:

Name:  Robert               Jhonson         21
Name:  Flex                 Maxed           23
Name:  Thisisaverylongname  andlongsurname  44

But what I'm trying to do is do not separate the surname in another column. This is the desired output:

Name:  Robert Jhonson                      21
Name:  Flex Maxed                          23
Name:  Thisisaverylongname andlongsurname  44

Do you have any idea to do it? Could you give me an example, please?

Was it helpful?

Solution

Using awk:

echo "$str1"|awk '{print $1, $2 " " $3, $4}' OFS='\t'
Name:   Robert Jhonson  21
Name:   Flex Maxed      23

EDIT: Based on edited question:

echo "$str1"|awk '{print $1, $2 " " $3, $4}' OFS='\t' | column -ts$'\t'
Name:  Robert Jhonson                      21
Name:  Flex Maxed                          23
Name:  Thisisaverylongname andlongsurname  44

OTHER TIPS

Here is a way in bash:

$ while read -r title fname lname age; do      
    echo "$title|$fname $lname|$age"
done <<< "$str1" | column -s'|' -t
Name:  Robert Jhonson                      21
Name:  Flex Maxed                          23
Name:  Thisisaverylongname andlongsurname  44

While reading you echo the line with new delimiters for column to put tabs on. Using -s option of column you specify the new delimiter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top