Home > OS >  How to find the unusual character ' using POSIX in bash?
How to find the unusual character ' using POSIX in bash?

Time:10-19

here are some names:

El Peulo'Pasa, Van O'Driscoll, Mike_Willam

how to filter the name contains ', using POSIX in bash by command find?

if I use the following command,

find . -maxdepth 1 -mindepth 1 -type d -regex '^.*[']*$' -print

Bash runs into a problem because the syntax ' will automatically convert the input to string

CodePudding user response:

You don't need -regex (which is a non-POSIX action) for this at all; -name is more than adequate. (-mindepth and -maxdepth are also extensions that aren't present in the POSIX standard).

To make a ' literal, put it inside double quotes, or in an unquoted context and precede it with a backslash:

find . -maxdepth 1 -mindepth 1 -type d -name "*'*" -print

...or the 100% identical but harder-to-read command line...

find . -maxdepth 1 -mindepth 1 -type d -name '*'\''*' -print

CodePudding user response:

If you're just searching the current directory (and not its subdirectories), you don't even need find, just a wildcard ("glob") expression:

ls *\'*

(Note that the ' must be escaped or double-quoted, but the asterisks must not be.)

If you want to do operations on these files, you can either use that wildcard expression directly:

dosomethingwith *\'*
# or
for file in *\'*; do
    dosomethingwith "$file"
done

...or if you're using bash, store the filenames in an array, then use that. This involves getting the quoting just right, to avoid trouble with other weird characters in filenames (e.g. spaces):

filelist=( *\'* )
dosomethingwith "${filelist[@]}"
# or
for file in "${filelist[@]}"; do
    dosomethingwith "$file"
done

The note here is that arrays are not part of the POSIX shell standard; they work in some shells (bash, ksh, zsh, etc), but not in others (e.g. dash). If you want to use arrays, be sure to use the right shebang to get the shell you want (and don't override it by running the script with sh scriptname).

  • Related