kdubs
kdubs

Reputation: 946

Run bash command on multiple files at once

I have a bunch of files that end in numbers (ex filename_01.txt, filename_02.txt, etc). Is there a way to run a bash command on a subset of these files in one call? Ie pseudo code:

cp filename_0{1:4} new_dir/

Thanks!

Upvotes: 1

Views: 584

Answers (2)

ghoti
ghoti

Reputation: 46826

Looking at two ways you can match files -- one with curly braces, and one with square braces. It's good to understand the difference.

cp filename_0{1..4} new_dir/

This expands into four filenames. Preface the command line with echo to see what you're actually running.

cp filename_0[1-4] new_dir/

This expands into all the existent files that match the pattern.

This isn't so subtle a difference. In the first case, if any file is missing, you'll see an error. In the second case, your command line will match all the files that exist, but there's no requirement for them to exist. If getting an error is important to you (because all these files should exist), choose your method accordingly.

Note that the curly brace notation, at least in bash version 4, can also handle increments, so you can do the following:

$ echo file{10..30..4}
file10 file14 file18 file22 file26 file30

I should point out that the [1-4] notation, while it looks like it might be part of a regular expression, is not. It's part of Pathname Expansion, documented fully in the bash man page (man bash). You should probably read about failglob and extglob while you're in a documentation-reading mood.

I should point out that neither of these cases handles zero padding on its own. In your example, and in the answers so far (including mine), the numbers are zero padded manually. If you want a more flexible approach that lets you work with arbitrary/unknown numbers of digits, you'll need to use a more advanced tool, presumably that understands printf-style formats. But that's probably an answer for another question. :-)

Upvotes: 2

SLePort
SLePort

Reputation: 15461

You can use brackets to expand file names :

cp filename_0[1-4].txt new_dir/

will copy filename_01.txt, filename_02.txt, filename_03.txt, filename_04.txt to new_dir.

Upvotes: 2

Related Questions