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?
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 outputprintf "\n"
: new line.Sample usage:
$ ./script_name < input_file > output_file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With