Skip to content

Instantly share code, notes, and snippets.

@m0un10
Created January 27, 2024 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m0un10/d5c1287dfaa4668b624b3d691341110c to your computer and use it in GitHub Desktop.
Save m0un10/d5c1287dfaa4668b624b3d691341110c to your computer and use it in GitHub Desktop.

Bash things I always forget...

Query

Tokenize with specific delimeter and select specific item (awk)

echo "sads/sadsad/sd" | awk -F/ '{print $1}
# sads

Tokenize with specific delimeter and retrieve and select a specific item (cut)

echo "sads/sadsad/sd" | cut -d/ -f2
# sadsad/sd

Tokenize with specific delimeter and retrieve the a range of indexes (cut)

echo "sads/sadsad/sd" | cut -d/ -f1-2
# sads/sadsad

Find & Query

Largest files in directory

du -h -d 1 | sort -hr

Find & Replace

Recursively find and replace

find . -type f -exec sed -i 's/FIND_TOKEN/REPLACE_TOKEN/g' {} \;

Appendix A: Referencible snippets

Add the below to ~/.bash_profile and type ref enter to get a list of referencible code snippets.

Then type ref_<name> (e.g. ref_shebang) to have it copy the snippet to the clipboard so you can paste it and use it accordingly.

alias ref_shebang="echo '#!/usr/bin/env bash' | pbcopy"
var_script_dir=$(cat << 'EOF'
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
EOF
)
alias ref_script_dir='echo "${var_script_dir}" | pbcopy'
alias ref_find_with_remove="echo 'find . -name \"*.txt\" -exec rm -i {} \;' | pbcopy"
alias ref_git_branch="echo 'git rev-parse --abbrev-ref HEAD' | pbcopy"
alias ref_git_sha="echo 'git rev-parse HEAD' | pbcopy"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment