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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can do this with
awk: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, ea,b,c,1337,d,ea, (many spaces) b, c,1337,d, eOFS=", ": 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--) { ... }:NFmeans 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 theOFSif it’s not the last field in the outputprintf "\n": new line.Sample usage: