Randomize the comma separated string in shell
I am newbie to Linux.I wanted to randomize the comma separated string.
String like "test1,test34,test5,test6".And it would be displayed differently when I ran each time. Expected output like "test5,test6,test1,test34". |
Code:
echo "test1,test34,test5,test6" | tr ',' "\n"|shuf|tr "\n" "," |
Shuf Command is not finding in shell.Is there any other way to achieve this.
|
Well, you can also do:
Code:
echo "test1,test2,test3,test4" | tr , "\n" | sort -R | tr "\n" , |
thank you for this solution
But i want like that each time when we run the script the order of words should be shuffled randomly. one time we run the script the order will be ===> "test1,test3,test4" another time when script will run again order should be changed like ==> "test3,test4,test1" |
Code:
bash-4.1$ echo "test1,test2,test3,test4" | tr , "\n" | sort -R | tr "\n" , |
hi,
sort -R command is not found due to which it is showing invalid -R command is there any other way for doing the shuffling randomly |
Not that I know of. You don't have shuf, you don't have sort ... can't think of anything else, except doing it manually.
|
Hi,
This is a bit longer one. echo test1,test2,test3,test4,test5 | tr ',' '\n' | awk 'BEGIN { srand() } { print rand() "\t" $0 }' | sort -n | cut -f2- | tr '\n' ','; echo |
Thanks for your solution
but one problem is coming after running the script, it is appending comma in last word test1,test2,test3,test4,test5, how to remove this comma in last word and how to assign the output in some other variable like tmp=echo test1,test2,test3,test4,test5 | tr ',' '\n' | awk 'BEGIN { srand() } { print rand() "\t" $0 }' | sort -n | cut -f2- | tr '\n' ','; echo |
To remove , you can add sed 's/,$//'
temp=$(echo test1,test2,test3,test4,test5 | tr ',' '\n' | awk 'BEGIN { srand() } { print rand() "\t" $0 }' | sort -n | cut -f2- | tr '\n' ',' | sed 's/,$//') |
hi,
this looks fine but it is not working in array it is giving the same order it is not showing the random order of array elements but is there any way to randomly shuffle the array elements directly without converting it as string |
Code:
BEGIN{srand();FS="," } Code:
$ echo test1,test2,test3,test4,test5| awk -f test.awk |
Thanks mario.almeida your solution..
|
All times are GMT -5. The time now is 11:48 PM. |