Using bash wildcards

Bash - GNU Shell, Tips View Comments

Common way for rename a mispelled file is to use mv but many dudes will first write the curent name then the new name (ie. mv old_file new_file). Stop ! Use the wildcards ! :-)

Most used wildcard is the asterix “*” (match all characters) but other usefull wildcards exist like the question mark “?” that match for a single character. In some case, as a large directories, that’s avoid you to use a grep on your ls command and give you a more concise listing.

# Question Mark Wildcard “?”

nicolas@grimm:~$ ls

pic1.jpg pic1.txt pic2.jpg pic3.jpg pic4.jpg pic5.jpg pic-big.jpg pic.jpg pic-small.jpg pic.txt pic1.txt pic2.txt pic1.bmp
nicolas@grimm:~$ ls pic?.jpg

pic1.jpg pic2.jpg pic3.jpg pic4.jpg pic5.jpg

Other usefful wildcard will be square brackets “[]” and curly brackets “{}“. First let you match a range of values, second let you define a list of values.

# Square Brackets Wildcard “[]“

nicolas@grimm:~$ ls pic[ 1-3].jpg

pic1.jpg pic2.jpg pic3.jpg

# Curly Brackets Wildcard “{}”

nicolas@grimm:~$ ls pic1.{txt,jpg,bmp}

pic1.txt pic1.jpg pic1.bmp

You can use those wildcards simultanously for a better search.

nicolas@grimm:~$ ls pic[1-3].{txt,jpg}

pic1.jpg pic1.txt pic2.jpg pic3.jpg

We have seen how to perform our ls search but you can also use those bash wildcards in any of your bash commands !

nicolas@grimm:~$ mv a_too_{short,long}_file_name_with_lot_of_ch4r4ct3r3.txt

will result in renaming the file a_too_short_file_name_with_lot_of_ch4r4ct3r3.txt to a_too_long_file_name_with_lot_of_ch4r4ct3r3.txt

nicolas@grimm:~$ cp pic[1-3].jpg dest

will result in copying pic1.jpg, pic2.jpg and pic3.jpg into the directory dest

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in