admin管理员组

文章数量:1301582

Using bash shell: Instead of ls *.{html,txt,pdf} (which results in e.g. a.txt b.pdf c.html) I would like to use something more adaptable like exts="html,txt,pdf" ; ls *.{$exts}. But the output of this is ls: cannot access '*.{html,pdf,txt}': No such file or directory. How can I get the correct result with a variabe as list of extensions?

Using bash shell: Instead of ls *.{html,txt,pdf} (which results in e.g. a.txt b.pdf c.html) I would like to use something more adaptable like exts="html,txt,pdf" ; ls *.{$exts}. But the output of this is ls: cannot access '*.{html,pdf,txt}': No such file or directory. How can I get the correct result with a variabe as list of extensions?

Share Improve this question edited Feb 11 at 14:01 Álvaro González 147k45 gold badges277 silver badges376 bronze badges asked Feb 11 at 13:09 SandwichXSandwichX 617 bronze badges 5
  • 2 This question lacks context. Which programming language or tool are you referring to? Which feature of it? – trincot Commented Feb 11 at 13:13
  • This question is similar to: Variables as commands in Bash scripts. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Justinas Commented Feb 11 at 13:17
  • I think it's not about 'variables as commands' but 'variables as argument-lists in commands'. – SandwichX Commented Feb 11 at 13:50
  • In bash you cannot use a variable inside a brace expansion; you would need to evaluate it, which is kind of dangerous – Fravadona Commented Feb 11 at 13:51
  • 1 The most upvoted answer to Brace expansion with variable? may be useful for you. – pjh Commented Feb 11 at 16:20
Add a comment  | 

2 Answers 2

Reset to default 5

One option is to use the "extended globbing" feature supported by Bash. (See the extglob section in glob - Greg's Wiki.)

shopt -s extglob
exts='html|txt|pdf'
ls *.@($exts)

Use find:

exts=html,pdf,txt; find . -regextype posix-extended -regex ".*\.(${exts/,/|})$" -printf '%f\n'

本文标签: bashVariable inside bracesStack Overflow