How do I remove keys?
Solution 1
This is not a feature right now to be able to do in one shot (see the comments in the DEL
documentation). Unfortunately, you are only left with using KEYS
, looping through the results, and then using DEL
to remove each one.
How about using bash a bit to help?
for key in `echo 'KEYS user*' | redis-cli | awk '{print $1}'`
do echo DEL $key
done | redis-cli
To step through it:
-
echo 'KEYS user*' | redis-cli | awk '{print $1}'
-- get all the keys and strip out the extra text you don't want with awk. -
echo DEL $key
-- for each one, create an echo statement to remove it. -
| redis-cli
-- take the DEL statements and pass them back into the cli.
Not suggesting this is the best approach (you might have some issues if some of your usernames have spaces in them, but hopefully you get the point).
Solution 2
Another compact one-liner I use to do what you want is:
redis-cli KEYS "user*" | xargs redis-cli DEL
Solution 3
Now there is a command to remove a key,i.e., DEL key [keys]
Solution 4
Using awk
, find all matching keys from redis using redis-cli KEYS
command and pipe to redis-cli DEL
command.
redis-cli KEYS "user*" | awk '{ system("redis-cli DEL " $1) }'
Solution 5
Further to orangeoctopus' answer, you don't need the echo
and pipe, you can pass commands as arguments into redis-cli
. This means you can do
for key in `redis-cli "KEYS" "user*" | awk '{print $1}'`
do redis-cli "DEL" "$key"
done
TIMEX
Updated on June 24, 2021Comments
-
TIMEX almost 3 years
I want to remove keys that match "user*".
How do I do that in redis command line?