0

I have the following data in my file

alice bob cathy david elon
unix linux bsd

I want output with only the last Nth instance of delimiter (ie. a space) being arranged

Like for last instance of delimiter (space)

alice bob cathy david     elon
unix linux                bsd

or for second last instance of delimiter (space)

alice bob cathy     david elon
unix                linux bsd

1 Answers1

1

When your data is delimited by ::

perl -F'[:]' -lane '
   push @e, join $", splice @F, -1;
   push @A, join $", @F;
   length($A[-1]) > $maxW and $maxW = length($A[-1])}{
   print $_, $" x ($maxW - length), "\t", shift @e for @A;
' file

Results

alice bob cathy david   elon
unix linux              bsd

when you want the last 2 elements to be separated, then change the -1 in the splice arguments list to -2, resulting in:


alice bob cathy david elon
unix            linux bsd

Explanation

  • Maintain the array @e that holds the last-Nth elements for each line.
  • Maintain the array @A that holds eachh line after the last-N elements have been pruned from the current line.
  • We determine the maximum width of these pruned lines.
  • After all lines have been read, we print each pruned line + differential spaces such that pruned-line lengths are equalized (after right padding spaces) + TAB + last-N elements.
  • How do I change delimiter from space to any other thing like ( or : – GypsyCosmonaut Jul 20 '17 at 12:40
  • I did not understand, could you please add an example in your answer replacing spaces with : delimiter in the file and then your code ? Thank you for helping. – GypsyCosmonaut Jul 20 '17 at 13:07
  • 1
    @GypsyCosmonaut I've modified the answer. Note however, the output is still space separated and not ":" separated. –  Jul 20 '17 at 13:13