Bash Pattern Searching Reference (PAL Series)

Update: These were written for my students while my role was a PAL (Peer Assisted Learning) Leader for my course, I intended to keep all the basic/intermediate commands necessary for terminal use in one place to ease the students into using Linux efficiently. I’ve kept them up just in case they’re of use to someone.

Wildcards

* – Match anything
? – Match a single character

$ ls
render_10.exr render_13.exr scene_10.tif scene_9.exr
render_11.exr render_14.exr scene_11.exr scene_9.tif
render_12.exr scene_10.exr scene_11.tif
$ ls scene*       # Match any file beginning with "scene"
scene_10.exr scene_11.exr scene_9.exr
scene_10.tif scene_11.tif scene_9.tif
$ ls *.exr        # Match any file ending with ".exr"
render_10.exr render_12.exr render_14.exr scene_11.exr
render_11.exr render_13.exr scene_10.exr scene_9.exr
$ ls scene_?.tif  # Match scene_1.tif, scene_2.tif, scene_3.tif etc but not scene_10.tif
scene_9.tif
$ ls scene_??.tif # Match scene_10.tif etc but not scene_1.tif etc
scene_10.tif scene_11.tif

Grep

Allows for much more powerful pattern matching than wildcards alone, but you need to learn regular expressions to really utilise it’s power.

A simple usage however is to search the output of a command

$ history | grep "touch *"
 2006 touch output.exr 
 2011 touch {a,b}{x,y,z}
 2013 touch {a,b}/{x,y,z}
 2021 touch {a,b}/{x,y,z}
 2022 touch {a,b}{x,y,z}

You can also use it directly on a file to search just that file

$ grep TARGET tracer.pro      # Search for string "TARGET" in tracer.pro 
TARGET=tracer
 QMAKE_EXTRA_TARGETS += first copydata
 PRE_TARGETDEPS+=C:/NGL/lib/NGL.lib