Select Targets for Bash Command
28 Sep 2019 Linux tipsshellThis post introduces how apply Linux commands to selective targets.
First of all are the well-known wildcards:
?for one any character*for zero or more characters
Next is to select few targets (without common pattern in names) by brackets, for example:
ls -l {foo,bar}
It is also possible to use it for part of the name as well as with wildcards together as shown in following example:
ls -l test{???,color}.cpp
And couple more advanced examples on nesting and listing:
mkdir -pv /{media/{floppy,cdrom},sbin,srv,var}
mkdir -pv /usr/{,local/}share/man/man{1..8}
The former has outer brackets,
while makes 4 directories (sbin, srv, var, and media) in the root partition,
and inner brackets for floppy, cdrom under /media.
The second example command summarizes man1, man2 until man8 with man{1..8}.
It is also worth mention that {,local/} is how to get both of the paths with or without local/ in between.
In addition, reverse selection is achieved by !.
The following command list all the files with .cpp suffix except those contain exactly 4 characters or _ in the basename:
ls -l !(????|*_*).cpp
Note, you may need to enable this by command:
shopt -s extglob
Credits
- list all files with extension .log except one - Thanks to choroba for the answer.
- How to exclude some files from filename expansion mechanism in bash? - Thank jimmij for the answer.
- LFS-BOOK - The trick to select few targets all together by brackets is frequently used in commands of the LFS book.
