1

I'm pretty sure I've seen this done before but I can't remember the exact syntax.

Suppose you have a couple of files with different file extensions:

foo.txt
bar.rtf
index.html

and instead of doing something with all of them (cat *), you only want to run a command on 2 of the 3 file extensions.

Can't you do something like this?

cat ${*.txt|*.rtf}

I'm sure there's some find trickery to identify the files first and pipe them to a command, but I think bash supports what I'm talking about without having to do that.

3
  • Note - that's file extensions. You can also use the file command to get the actual type by inspection. Commented Oct 12, 2015 at 13:19
  • @Sobrique updated my question to be more correct. Commented Oct 12, 2015 at 13:23
  • You might also be thinking find -exec and xargs to run commands on a list. Commented Oct 12, 2015 at 13:25

3 Answers 3

4

The syntax you want is cat *.{txt,rft}. A comma is used instead of a pipe.

$ echo foo > foo.txt
$ echo bar > bar.rft 
$ echo "bar txt" > bar.txt 
$ echo "test" > index.html
$ cat *.{txt,rft}
bar txt
foo
bar
$ ls *.{txt,rft}
bar.rft  bar.txt  foo.txt

But as Anthony Geoghegan said in their answer there's a simpler approach you can use.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I was looking for, so thanks, although I may or may not use shell globbing. Thanks!
I've upvoted this as I didn't realise you could use Bash's curly braces expansion in conjunction with regular POSIX shell globbing.
2

Shell globbing is much more basic than regular expressions. If you want to cat all the files which have a .txt or .rtf suffix, you'd simply use:

cat *.txt *.rtf

The glob patterns will be expanded to list all the filenames that match the pattern. In your case, the above command would call the cat command with foo.txt and bar.rtf as its arguments.

Comments

0

Here's a simple way i use to do it using command substitution. cat $(find . -type f \( -name "*.txt" -o -name "*.rtf" \)) But Anthony Geoghegan's answer is much simpler. I learned from it too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.