I have been working off of this question: How To Randomly Choose Strings From Same Line In File and we are able to randomly select 1-2 strings. But, I'm stuck trying to return 0-2 strings.
Here's the code I'm working with:
while read -r line; do
elements=(`echo "$line" | grep -oP '(#\S+)' | shuf`)
show="${elements[$((RANDOM % ${#elements[@]}))]}"
if (((RANDOM % 2) == 0)); then
elements=(`echo ${elements[@]//$show}`)
show+=" ${elements[$((RANDOM % ${#elements[@]}))]}"
fi
echo "$show"
done < file1.txt
My attempt:
cat file1.txt | while read -r line;
do elements=(`echo "$line" | grep -oP '(#\S+)' | shuf`);
show="${elements[$((RANDOM % ${#elements[@]}))]}";
if (((RANDOM % 2) != 0));
then show+=" ${elements[$((RANDOM % ${#elements[@]}))]}";
fi;
echo "$show";
done | awk '{ while(++i<=NF) printf (!a[$i]++) ? $i FS : ""; i=split("",a); print ""}'
Here's file1.txt:
#Sample #Example #StackOverflow #Question
#Easy #Simple #Code #Examples #Help
#Support #Really #Helps #Everyone #Learn
It would randomly output:
#Question
#Code #Examples
#Helps
Let's say, I want to have no strings returned randomly:
#Simple #Examples
#Everyone
I know it has to do with the logic of if there are 0, but can't get it to return 0 results. If you guys can point me in the right direction. I would appreciate the input and support of the question.
Aucun commentaire:
Enregistrer un commentaire