Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash reverse order of comma separated values

Tags:

bash

I've got the following list of elements:

a, b, c, 1337, d, e

I wish I have:

e, d, 1337, c, b, a

How can I achieve that in bash?

like image 762
Dejwi Avatar asked Nov 13 '12 19:11

Dejwi


1 Answers

You can do this with awk:

#!/bin/bash

awk 'BEGIN{FS=",[ ]*"; OFS=", "}
    {
        for (i=NF; i>0; i--) {
            printf "%s", $i;
            if (i>1) {
                printf "%s", OFS;
            }
        }
        printf "\n"
    }'

Explanation of the script:

  • FS=",[ ]*";: The regex for Field Separator (delimiter for your input) matches a comma followed by zero or more spaces, so your input can be any of:
    • a, b, c, 1337, d, e
    • a,b,c,1337,d,e
    • a, (many spaces) b, c,1337,d, e
  • OFS=", ": The Output Field Separator (delimiter for your output) will be explicitly a comma followed by a space (so output looks consistent)
  • for (i=NF; i>0; i--) { ... }: NF means the Number of Fields in the current line. Here we iterate backwards, printing from the last field to the first field.
  • if (i>1) { ... }: Only print the OFS if it's not the last field in the output
  • printf "\n": new line.

Sample usage:

$ ./script_name < input_file > output_file
like image 188
sampson-chen Avatar answered Sep 22 '22 23:09

sampson-chen