Home > other >  Pathname expansion with multiple criteria in Bash
Pathname expansion with multiple criteria in Bash

Time:10-10

Suppose that there are these files in my directory:

a1x
albtmk
axxxxx
blabla
bb

I would like to use ls based on some criteria and then print the output using echo. Criteria are:

  1. File name has three and more characters,
  2. file name starts on vowel,
  3. penultimate character is not a number.

So, desired output is albtmk axxxxx.

What I tried so far:

MYFILES=`ls a??* e??* i??* o??* u??* y??* A??* E??* I??* O??* U??* Y??*`

echo $MYFILES

I would like to ask:

  1. Can I combine a??* e??* i??* o??* u??* y??* A??* E??* I??* O??* U??* Y??* together?
  2. How can I form the condition penultimate character is not a number ? Somehow using regex?

CodePudding user response:

No, you don't need regular expressions here.

ls [AEIOUYaeiouy]*[!0-9]?

CodePudding user response:

With bash:

  • You can use a case-insensitive globbing pattern.
  • Store the list of files matching the pattern into an array.
  • Print the array elements into a space-delimited list.
#!/usr/bin/env bash

# Query and save nocaseglob state
shopt -q nocaseglob && nocaseglob=1

# Make globbing patterns expands case insensitively
shopt -s nocaseglob

# Populate the myfiles array with all files matching the pattern
myfiles=( [aeiouy]*[!0-9]? )

# Restore nocaseglob state
[ "$nocaseglob" ] || shopt -u nocaseglob

# Print all myfiles entries in the same line:
printf %s\\n "${myfiles[*]}"

Note from inian:

saving nocaseglob status and restoring is needed only if the script needs to be sourced. For a normal executed shell script, it isn't required.

CodePudding user response:

Use find with regular expressions:

find . -regex '\./[aeiouyAEIOUY].*[^0-9].$'
  •  Tags:  
  • bash
  • Related