I'd like to write a Posix shell script function that will match on a pattern with both spaces and glob characters (*?) that need to be expanded. In Python, glob.glob('/tmp/hello world*') will return the correct list. How do I do this in the shell?
#!/bin/sh
## this function will list
## all of the files in the /tmp
## directory that match pattern
f() {
PATTERN="$1"
ls -1 "/tmp/$PATTERN"
}
touch '/tmp/hello world {1,2,3}.txt'
f 'hello world*'
You can enclose everything except the *
in quotes:
ls -l "hello world"*
ls -l "hello world"*".txt"
You can then pass a quoted string to f()
. Using the string inside f()
will require eval
.
#!/bin/sh
## this function will list
## all of the files in the /tmp
## directory that match pattern
f() {
PATTERN=$1
eval ls -1 "/tmp/$PATTERN"
}
touch '/tmp/hello world {1,2,3}.txt'
f '"hello world"*'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With