Columns

分隔符最後第 N 個實例旁邊的列排列

  • July 20, 2017

我有以下數據file

alice bob cathy david elon
unix linux bsd

我只想輸出最後一個分隔符的第 N 個實例 (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

``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.``

引用自:https://unix.stackexchange.com/questions/379720