Ubuntu – Terminal: Avoid repeating directory multiples times to reach files within

bashcommand line

I have two files file1.txt , flie2.txt in a directory X. I want to copy those files to my current working directory which is far away from the directory X.

so I end up with a command like:

cp ~/Desktop/dir/dir/dir/dir/file1.txt ~/Desktop/dir/dir/dir/dir/file2.txt .

Is there anyway to use the directory path once for both file, some kind of a shortcut ?
I am sure there is, Ubuntu never failed my laziness 😀

Best Answer

Use [1-2] to indicate the files, this uses bash's range expansion feature :

cp ~/Desktop/dir/dir/dir/dir/file[1-2].txt .

Here the range [1-2] will expand so file[1-2].txt will expand to file1.txt and file2.txt.

Note that if you have multiple files like this with various number of numeric digits among their names :

file1.txt file12.txt file980.txt file0.txt file23.txt 

In this case use the extglob feature of bash to enable extended pattern matching:

$ shopt -s extglob

$ cp ~/Desktop/dir/dir/dir/dir/file+([0-9]).txt .

The extglob pattern +([0-9]) will match one or more digits between file and .txt in the file names.

Also note that it does not depend on any prefix or suffix, for example if you have files having names:

1 02 043 908

These can be matched (and copied) too by :

$ cp ~/Desktop/dir/dir/dir/dir/+([0-9]) .

Check man bash to get more idea on this.