Michael Gruenstaeudl Michael Gruenstaeudl - 1 year ago 38
Bash Question

Inline reordering of substrings via bash

Assume a text file that contains specific lines whose word order should be altered. The words (substrings) are delimited by single whitespaces. The lines to be altered can be identified by their first character (e.g., ">").

# cat test.txt
>3 test This is
foo bar baz
foo bar qux
>2 test This is
foo bar baz
>1 test This is
foo bar qux

What command (probably in
) would you use to apply the same ordering process across all lines starting with the key character?

# cat test.txt | sought_command
>This is test 3
foo bar baz
foo bar qux
>This is test 2
foo bar baz
>This is test 1
foo bar qux

Answer Source

Here's one way you could do it using awk:

awk 'sub(/^>/, "") { print ">"$3, $4, $2, $1; next } 1' file

sub returns true (1) when it makes a substitution. The 1 at the end is the shortest true condition, to trigger the default action { print }.