Skip to content

Instantly share code, notes, and snippets.

@sorokine
Last active May 3, 2024 21:26
Show Gist options
  • Save sorokine/7b032ccb39514e2a64801f63d9ea36c2 to your computer and use it in GitHub Desktop.
Save sorokine/7b032ccb39514e2a64801f63d9ea36c2 to your computer and use it in GitHub Desktop.
My Cheatsheet

bash

  • ESC f - next word
  • ESC b - previous word
  • ^w - delete previous word
  • ^u - delete to line start
  • ^y - paste deleted
  • ESC d - delete next word
  • ESC t - swap words
  • ESC r - restore line
  • ESC # - comment out line
  • ESC * - insert file names in CWD starting with
  • ^x^e - invoke editor for the command
  • ^_ - undo edit
  • : "${VAR:=default}" - set variable if not already set
  • redirection
    • >&2 echo error - echo to stderr
    • 2>&1 - combine stdout and stderr
    • > >(tee stdout.log) 2> >(tee stderr.log) - redirect stdout and stderr to different files

top

git

  • git worktree add <branch> <dir - create another directory with a branch
  • git restore <branchtag|sha> -- <file> - restore deleted file
  • git log --graph --all - show graph with all branches
  • git show development:my_file.txt - show file in another branch
  • git whatchanged -p my_file.rb - See What Has Changed on a File Over Time
  • git rev-list --all | xargs git grep -F '' - grep all branches
  • remove all untracked and ignored files and empty directories
    git clean -fdX
    find . -type d -empty -delete

top

iTerm2

  • <Command> <Alt> <Mouse> - iTerm2 rectangular selection

top

Linux

  • find . -mindepth 1 -maxdepth 1 -type d -print0 | xargs -0 du -sh | sort -h - list sizes of all directories including ones with spaces
    • -iname - is like -name but case insesitive
  • ping 0 - check if network is running on the localhost
  • use /usr/bin/time -v instead of time to get more detaiiled process infrmation
  • sort a file keeping header at the top: cat file | (read -r; printf "%s\n" "$REPLY"; sort)
  • sudo lshw - list hardware
  • pipe through pv to see the command progress
  • findmnt to see mount points with details

Ubuntu

  • fix for command-not-found on Ubuntu
    sudo apt install --reinstall command-not-found
    sudo chmod -R o+r /var/lib/command-not-found/
  • remote logout console session gnome-session-quit --no-prompt
  • adduser
  • sudo usermod -a -G <group> <user>; newgrp <group> add user to a group and reload assignment
  • xsel - copy/paste from/to clipboard

MacOS

  • ⌘⇧. Command-Shift-. - show hidden files
  • ⌘⇧G Commnad-Shift-G in file dialog - enter path

top

neovim

  • gg/G - go to file start/end
  • 556G - go to line 556
  • n/N - find next/previous
  • :map - show keybindings
  • reload file
    • :edit - current buffer
    • :checktime - all files
  • :r file - insert text from file
  • ^w - window operations followed with
    • w - next window
    • v/s - vertical/horisontal split
    • o - minimize other windows
    • +/- - increase/decrease vertical size
    • </> - increase/decrease horisontal size
    • x - swap current window with the next
    • m - zoom/unzoom curren window
    • q - cancel window split
    • w - make all windows same size
  • :set scrollbind - sync scroll in windows
  • ^v - start rectangular selection
  • :let mapleader - detect <Leader> key
  • ^r - redo
  • find/replace
    • :%s/str/repl/gc - ask and replace
    • :%s/%Vstr/repl/g - search/replace within none-line selection
  • :set nowrap - prevent line wrapping
  • ^y/^e/^u/^d - scroll up/down/pg up/pg down
  • gc, move - comment/uncomment, if does not work
    • comment block: in the 1st column ^v, select block, I # Esc
    • uncomment block: in the 1st column ^v, select block, d Esc
  • "ayy/"Ayy - copy/append selection to register a
  • zR/zM - open/close all folds
  • zo/zc open/close current fold
  • >/< indent/unindent block
  • >>/<< indent/unindent line
  • ^r" insert register into command buffer
  • :so % - reload config while editing init.vim
  • F4 - ctags sidebar (:TagbarToggle)
  • F7 - run flake8
  • r - replace single character
  • % - jump to matching bracket
  • delete d/change c/yank y
    • di" - delete within quotes or other chracters
    • da" - delete within quotes and delete quotes
    • dtc - delete until chracter 'c'
    • df - delete until next space or other chracter including it
    • dT - delete backward until space or other character
    • daw - delete the whole word with space
    • diw - delte the whole word without space
  • quoting/unquoting
    • cs"' - change " to '
    • ds" - unquote "
    • ysiw" - quote word with "
  • ^o/^i - jump to previos/next location (normal mode)
  • fc/Fc - jump forward/back to character c
  • gqip - wrap current line
  • :noh - remove search highlight
  • macro
    • qaq - start where 'a' is a regizter a-z
    • N@a - play macro in register 'a' 'N' number of times
  • ^6 - switch to previous buffer
  • * - search for the word under cursor
  • marks
    • ma - mark position a
    • `a - jump to position a
    • 'a - jump to line of position a
    • `. - jump to last edit
  • ^ - move to 1st none-space character of the string
  • INSERT mode
    • ^r* - insert yanked text
    • ^o - perform a single command from NORMAL mode
  • r! date - insert current timestamp
  • gx - open browser on the current link
  • bw - completely close the file
  • :help - get help on a topic
    • ^] - follow the link
    • ^T - go back
    • ^o/^i - history forward/back
  • :argdo/:bufdo/:windo/tabdo - run operation on multiple files
  • ^l - redraw screen

git/fugitive

  • [/]c - jump prev/next hunk
  • ,hs - stage current hunk
  • ,hu - unstage current hunk
  • :G - start commit
  • ca in status window on commit -- amend

NERDTree

  • ma - create a file in the selected directory
  • :syntax on - fix weird symbols in the file list

DrawIt

  • ,di - start line drawing mode
  • ,ds - stop line drawing
  • <,>,^,v - arrows
  • ^v, draw block
    • ,b - draw a box
    • ,l - create a box
    • ,f - flood with character (does not work)

dbext

  • ,sdt - describe table
  • ,se - execute selection or statement under cursor
  • :DBCompleteTables - load table names for completion

Spellchecker & Thesaurus Query

  • :setlocal spell spelllang=en_us - start spellcheck
  • z= - spelling suggestions
  • zg - add misspelled word to local dictionary
  • ]s/[s - move to next/previous misspelled word
  • ,cs - on the word for list of synonyms, etc.

LatexBox

  • \lv - Latex view
  • \lt - Latex TOC
  • % - jump matching bracket
  • ^X^O - complete

xml-plugin

  • % - jump between '<' and '>'
  • > - complete single line tag
  • >> - complete multiline tag
  • \x - surround selection with a tag
  • \% - jump to tag start
  • \d - delete surrounding tags
  • \c/\u - comment/uncomment selection

top

PostgreSQL/PostGIS

  • fast count of rows estimate
    SELECT reltuples::bigint AS estimate FROM pg_class WHERE relname = 'table_name';
  • poor man's histogram:
    SELECT width_bucket(numeric_column, 1, 200, 20), count(*)
    FROM table GROUP BY 1 ORDER BY 1
  • split_part('a:b', ':', 1) -> a
  • concat_ws(':', 'a', 'b', ..) - join strings with seprator
  • stop/kill query
    SELECT * FROM pg_stat_activity WHERE state = 'active';
    SELECT pg_cancel_backend(<pid of the process>)
  • convenient view for background queries
    SELECT 
      now()-query_start as elapsed, 
      state, datname, pid, usename, 
      query, application_name, client_addr, 
      query_start, state_change, 
      wait_event_type, wait_event 
    FROM pg_stat_activity WHERE state = 'active';

top

Python

  • import ipdb; ipdb.set_trace() - drop into iPython
  • create virtual environment - https://docs.python.org/3/library/venv.html
    python3 -m venv --upgrade-deps venv && \
    . ./venv/bin/activate
  • install requirements
    pip install -r requirements.txt
  • find all python environments in current directory and below
    fd -p -g '**/bin/activate'
  • aList[::-1] - reverse a list
  • create conda environment:
    conda create -n <env> python=3.12 pip 
    conda activate <env>
  • useful decorators
    @atexit.register
    @dataclass
    @unique
    @singledispatch
  • clickable terminal links
    import rich
    rich.print("Hello [link=http://localhost:8000]App[/link]!")

Pandas

  • replace column names: df.columns = ['a', 'b', 'c']
  • insert top row
    df.loc[-1] = [1,2,3]
    df.index = df.index + 1
    df = df.sort_index()
  • drop empty rows: df.dropna(axis='rows', inplace=True, how='all')

top

tmux

  • ^B I - Installs new plugins from GitHub or any other git repository
  • ^B U - updates plugin(s)
  • ^B alt u- remove/uninstall plugins not on the plugin list
  • ^B [ - scroll/copy mode
    • q - quits
    • ^<space> - start higlight
    • <esc>w - copy highlighted text
  • ^B %/| - split vertical/horizontal
  • ^B <-/^B -> - move between windows
  • ^B z - zoom pane to the whole window
  • ^B / - search
  • ^B y - copy command to clipboard
  • ^B Y - copy PWD to clipboard
  • ^B C - create new session from within the currebt one
  • ^B g - switch to another session
  • ^B ] - paste from clipboard
  • ^B b - last window
  • ^B <space> - change layout
  • save buffer in file: ^B:capture-pane -S -3000<enter>^B:save-buffer file.txt<enter>
  • ^B D - disconnect other clients
  • tmux new-session -A -s NAME - create new or attach to existing named session

byobu

  • byobu-tmux - start byobu with tmux CLI options
  • ^B |/% - horizontal/vertical split
  • Enter - copy highlight

top

zsh

  • [tab] - file name globs (requires setopt extendedglob)
    • <200-300> - range of integers
    • ^*.c - negate glob
    • ~ - exclude from pattern
    • **/* - get into subdir
  • =<command> - $(which <command>)
  • fc - run the editor on previous command
  • r a=b - rerun previous command with optional substitution
  • [ESC]q - put command on stack
  • [ESC]a - execute command keep it in buffer
  • [ESC]' - escape command

top

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment