Using Raku (formerly known as Perl_6)
raku -ne 'join( "\t", .words[0..*-3], .words[*-1] // "", .words[*-2] // "").trim-leading.put ;'
Basically, the code above creates a list of whitespace-separated elements (words
) in the desired order (last two elements switched). The elements are join
ed with \t
tab, any leading whitespace is trimmed away with trim-leading
, and the result is output
. This code works on tab-separated columns as well as on space-separated columns.
Note, Raku's //
defined-OR operator is used to avoid issues with Nil
values in String context--an ""
empty string is 'inserted' where necessary.
Sample Input (first line is blank):
A
A B
A B C
A B C D
A B C D E
A B C D E F
Sample Output (last two elements on each line are swapped--first line is still blank):
A
B A
A C B
A B D C
A B C E D
A B C D F E
https://docs.raku.org/routine/words
https://docs.raku.org/routine/join
https://raku.org