qr code

BIT-101

Bill Gates touched my MacBook Pro

Command Line Tricks


[ tips ]

Just a bunch of useful command line scripts to do various things. These are all prime candidates for aliases.

For example, I alias du -d 1 | sort -hr | column -t -R 1 -N Size,Folder -l 2 to dui. The i doesn’t stand for anything, but it’s easy to remember!

Find examples

Find files by name.

Can add -type f or -type d to only look for files or directories.

Simple glob patterns, not regex.

find . -name "*foo*"

Case insensitive

find . -iname "*foo*"

Regex

find . -regex ".*foo.*"

Matching multiple names with AND.

find . -name "*foo*" -and -name "*bar*"

Shorter…

find . -name "*foo*" -a -name "*bar*"

And is implied.

find . -name "*foo*" -name "*bar*"

Matching multiple names with OR.

find . -name "*foo*" -or -name "*bar*"

Shorter…

find . -name "*foo*" -o -name "*bar*"

Reject file name matches. Can use -and or -a here too.

find . -name "*foo*" -not -name "*foo-bar*"

Find files by extension.

find . -name "*.ext"

Count of files only.

find . -type f | wc -l

Count of folders only.

find . -type d | wc -l

List all file extensions in a folder.

Simple

find . -type f | sed -e 's/.*\.//' | sed -e 's/.*\///' | sort -u

With counts, and sorted

find . -type f | awk -F'.' '{print $NF}' | sort| uniq -c | sort -gr

Find all empty directories.

find . type -d -empty

Find all empty files.

find . type -f -empty

Find all directories that don’t have nested directories (leaf directories).

-links = 1 for current dir, 1 for parent dir, 1 for each nested dir.

find . -type d -links 2

Find all hidden files.

Hidden

find . -type f -name ".*"

NOT hidden

find . -type f -not -name ".*"

Find all hidden directories.

Hidden, ignoring current dir “.”

find . -type d -name ".*" -not -name "."

NOT hidden

find . -type d -not -name ".*"

Delete matches.

Be careful here!!!

find . -name "*foo*" -delete

List 10 largest files.

find . -type f -exec ls -lhS {} + | head -n 10

Other

Simple list of directory sizes.

dui -d 1 -h

Folder sizes sorted and tabulated. Change -d to control depth.

du -d 1 | sort -hr | column -t -R 1 -N Size,Folder -l 2

Run new command with arguments from the last command.

new_command $_
# or
new_command !$

Recall a specific argument from the last command.

# single
new_command !:n

# series
new_command !:n-m

# arbitrary
new_command !:n !:p
« Previous Post

Comments? Best way to shout at me is on Mastodon

Or share this post directly on Mastodon