5

I am trying to delete multiple keys from my remote Redis db using the following command.

redis-cli -h <host> -p 6379 KEYS "myprefix:*" | xargs redis-cli -h <host> -p 6379 DEL

It has deleted all the matching keys except the ones having spaces in them.

For e.g.

Deleted:

  • myprefix:abc
  • myprefix:def
  • myprefix:ghi

Not deleted:

  • myprefix:jkl mno
  • myprefix:pqr stu
  • myprefix:vwx yza

What should be my query pattern so that these get deleted too? I tried googling but was unable to find any solution.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
XCEPTION
  • 1,671
  • 1
  • 18
  • 38

3 Answers3

9

The issue is with xargs, not your KEYS query. If you run your query, you will notice that it correctly returns the keys with spaces in them. The problem is that by default xargs splits the strings piped into it by blanks and newlines. To change this behaviour so that it only delimits by newlines, add the -d "\n" option. For example:

redis-cli -h <host> -p 6379 keys "myprefix:*" | xargs -d "\n" redis-cli -h <host> -p 6379 del
cbp
  • 25,252
  • 29
  • 125
  • 205
  • 1
    The `-d` option doesn't exist in MacOS or GNU xargs. See [this answer](https://stackoverflow.com/a/32589977/558006) and its comments for workarounds. – brotskydotcom Oct 04 '20 at 19:39
1

For anyone using Mac OS xargs (BSD) instead of linux (GNU) xargs the following works

redis-cli -h <host> -p 6379 keys "myprefix:*" | xargs -I% redis-cli -h <host> -p 6379 del %

or for other weird characters like speech marks this works

redis-cli -h <host> -p 6379 --scan --pattern "myprefix:*" | tr '\n' '\0' | xargs -0 -I% redis-cli -h <host> -p 6379 del %

uosjead
  • 426
  • 6
  • 5
0

Here is an another hack to make it work on Mac.

redis-cli KEYS 'pattern*' | xargs -0 -n1 'echo' | sed "s/^/'/g" | sed "s/$/'/g" | xargs redis-cli DEL

This basically puts quote around your keys before passing to redis-cli DEL

pratpor
  • 1,954
  • 1
  • 27
  • 46