Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell glob expansion with spaces

Tags:

bash

shell

sh

glob

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*'
like image 476
Hal Canary Avatar asked Oct 15 '25 23:10

Hal Canary


1 Answers

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"*'
like image 117
craig65535 Avatar answered Oct 18 '25 15:10

craig65535



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!