Skip to content

Instantly share code, notes, and snippets.

@embayer
Last active May 28, 2017 09:56
Show Gist options
  • Save embayer/e18c16044d71bf4733399d0859120372 to your computer and use it in GitHub Desktop.
Save embayer/e18c16044d71bf4733399d0859120372 to your computer and use it in GitHub Desktop.
collection of cheat sheets

apps

slack

shortcuts

<cmd> / <ctrl> are equivalent

shortcutaction
<cmd-1>switch team
<cmd-k>quick switcher
<cmd-shift-k>direct message
<cmd-u>upload a file

slash commands

CommandAction
/shrug [your message]Appends ¯\_(ツ)_/¯ to your message
/keysOpen the keyboard shortcuts dialog
/search [your text]Search Slack messages and files
/me [your text]Display action text, e.g. “/me does a dance” will display “does a dance”
/msg user [your message]Send a private message to another user
/dm user [your message]Send a private message to another user
/awayToggle your “away” status
/muteMute a channel, or unmute a channel that is muted

more

CommandAction
/archiveArchive the current channel
/closeClose a channel or direct message
/collapseCollapse all inline images and video in the current channel (opposite of /expand)
/expandExpand all inline images and video in the current channel (opposite of /collapse)
/feed help [or subscribe, list, remove…]Manage RSS subscriptions
/feedback [your feedback]Send feedback to Slack
/invite @user [channel]Invite another member to a channel
/join [channel]Open a channel
/kick @useror
/remove @userRemoves user from the current channel. This action may be restricted to owners or admins.
/leaveClose a channel or direct message
/open [channel]Open a channel
/partClose a channel or direct message
/prefsOpen the preferences dialog
/remind me in [time] to [message]Set a Slackbot reminder that will send you a direct message at the time you specify.
/remind me to [message] at [time]To schedule a reminder for a specific date, use the format MM/DD/YYYY or DD.MM.YYYY.
/remind helpLearn more about how to set reminders.
/remind listGet a list of the reminders you’ve set.
/rename [new name]Rename a channel (admin only)
/shortcutsOpen the keyboard shortcuts dialog
/topic [text]Set the channel topic
/whoList users in the current channel

couchdb

list functions

HTML

document

{
    "_id": "_design/kw08",
    "language": "javascript",
    "views": {
        "all": {
            "map": "
                function(doc) {
                    if (doc.keywords === 'foo') {
                        emit(doc.asin, doc);
                    }
                }"
        }
    },
    "lists": {
        "summary": "
             function(head, req) {
                 var row;
                 start({
                     'headers': {
                     'Content-Type': 'text/html'
                     }
                 });
                 while(row = getRow()) {
                     send('<h2>'+row.value.asin+'</h2>');
                 }
             }"
   }
}

PUT

curl -X PUT http://localhost:5984/dbname/_design/ -d @documentname.json

GET

curl http://localhost:5984/products/_design/kw/_list/summary/all

emacs

general

help

<Ctrl-h> aget help for a command (word list or regexp)
<Ctrl-h> kdescribe key
<Meta-x> info <Enter>read the documentation

save

<Ctrl-x> <Ctrl-s>save the current buffer
<Ctrl-x> <s>save all buffers
<Ctrl-x> <Ctrl-w>save the current buffer with a specified filename

open

<Ctrl-x> <Ctrl-f>open/create file
<Meta-x> revert-bufferreload file in current buffer
<Meta-x> find-file-at-pointopen a uri

close

<Ctrl-x> <Ctrl-c>quit
<Ctrl-x> <k>kill buffer

copy paste

<Ctrl-w>copy
<Ctrl-y>paste
<Meta-w>cut

search and replace

<Ctrl-s>incremental search
<Ctrl-s>next candidat
<Meta-x> delete-trailing-whitespaceguess what

buffer

<Ctrl-x> <1>delete all other windows
<Ctrl-x> <o>switch buffer

source

<Ctrl-x> <Ctrl-e>eval sexp

lines

visual-line-modetoggle line wraps

packages

<Meta-x> list-packages <Enter>list available packages

re-builder

<Meta-x> re-builderstart regular expression builder
<Ctrl-c> <Ctrl-q>exit regular expression builder

evil-mode

<Meta-p>search history up
<Meta-n>search history down
/ <ctrl-y>paste text to search for

org-mode

help

http://orgmode.org/orgcard.pdf

<Meta-x> org-info <Enter>read the documentation

visibility

cycling

<Tab>rotate current subtree between states
<Shift-Tab>rotate entire buffer between states

initial document visibility

#+STARTUP:

overviewtop-level headlines only
contentall headlines
showallno folding of any entries
showeverythingshow even drawer contents

headline visibility

#+VISIBILITY:

foldedonly headline
childrenchild headlines
content
alleverything
* headline
    :PROPERTIES:
    :VISIBILITY: folded
    :END:

properties

org-set-propertyset property for cursor position context

motion

<Ctrl-c> <Ctrl-n/p>next/previous heading
<Meta-up>scroll to next page
<Meta-down>scroll to previous page
<Ctrl-l>focus the text around the coursor (can be repeated)

structure editing

<Meta-Shift-Up/Down>move subtree/list item up/down
<Meta-Enter>insert new heading/item at current level
<Ctrl-Enter>insert new heading after subtree
<Meta-Shift-Enter>insert new TODO entry (TODO |\vert - [ ])

markup

bold
italic
underlined
verbatim
code
‘+strike-through+’

tables

|–<Tab>insert seperating row
<Ctrl-c> <Ctrl-c>re-align the table without moving the cursor
<Tab>re-align the table, move to next field
<Shift-Tab>move to previous field
<Enter>re-align the table, move to next row
<Meta-Shift-Up/Down>move row up/down
<Meta-Left/Right>move the current column left
<Meta-Shift-Left>kill the current column
<Meta-Shift-Right>insert new column to left of cursor position
<C-u> <C-c> <|>convert selected region to table
C-c |create or convert from region
org-table-exportexport/convert table
\ vert (together)escape pipe (|)

formulas

<Ctrl-c> ?reference the current cell
<Ctrl-c> }turn on the reference visualization grid
<Ctrl-u> <Ctrl-c> *re-evaluate all formulas
:=vsum(@2..@9)sum of row 2 -9
:=vmean($1..$9)mean of column 1 - 9

links

<Ctrl-c> <Ctrl-l>insert a link (TAB completes stored links) / edit link at point
<Ctrl-u> <Ctrl-c> <Ctrl-l>insert file link with file name completion
<Ctrl-c> <Ctrl-o>open file links in emacs
<Ctrl-c> <Ctrl-l>edit link under the cursor

format

description or alternatively link

[[link][description]]
# or alternatively
[[link]]
# image
[[image]]

“TODO” Items

<Ctrl-c> <Ctrl-t>rotate the state of the current item
<Shift-Up/Down>raise/lower priority
<Ctrl-c> <Ctrl-c>toggle checkbox at point (- [ ] subtask)
<Meta-Shift-Enter>insert new TODO entry (TODO |\vert - [ ])

repeated tasks

** TODO Pay the rent
   DEADLINE: <2005-10-01 Sat +1m>

where y/w/m/d/h can be used

timestamps

<Ctrl-c> .prompt for a timestamp
<Ctrl-c> !prompt for an inactive timestamp
<Ctrl-c> <Ctrl-d>insert DEADLINE timestamp
<Ctrl-c> <Ctrl-s>insert SCHEDULED timestamp
<Shift-Right/Left>change timestamp at cursor ±1 day
<Shift-Up/Down>change year/month/day at cursor by ±1
<Ctrl-c> >access the calendar for the current date
<Ctrl-c> <insert timestamp matching date in calendar access agenda for current date

agenda

<Ctrl-c> <a> <a>agenda view
<l>log view
<q>quit

code blocks

<Ctrl-c> <Ctrl-c>execute code block under cursor

format

*+BEGIN_SRC org +BEGIN_SRC org echo “This file takes up `du -h emacs.md | sed ‘s/\([0-9k]\)[ ]*emacs.md/\1/’`” *+END_SRC *+END_SRC

supported languages

LanguageIdentifierLanguageIdentifier
AsymptoteasymptoteAwkawk
CCC++C++
ClojureclojureCSScss
Ddditaaditaa
GraphvizdotEmacs Calccalc
Emacs Lispemacs-lispFortranfortran
gnuplotgnuplotHaskellhaskell
JavajavaJavascriptjs
LaTeXlatexLedgerledger
LisplispLilypondlilypond
MATLABmatlabMscgenmscgen
Objective CamlocamlOctaveoctave
Org modeorgOzoz
PerlperlPlantumlplantuml
Processing.jsprocessingPythonpython
RRRubyruby
SasssassSchemescheme
GNU ScreenscreenSedsed
shellshSQLsql
SQLitesqlite

tags

heading tags

<Ctrl-c> <Ctrl-q>set tags for current heading
<Ctrl-u> <Ctrl-c> <Ctrl-q>realign tags in all headings
<Ctrl-c> <\>create sparse tree with matching
<Ctrl-c> <Ctrl-o>tags globally (agenda) match tags at cursor
org-change-tag-in-regionset tags for selected headings

priority

<Shift-Up/Down>set prio for header

sort

Sorting methods: Alphabetically, numerically, by time (first timestamp with active preferred, creation time, scheduled time, deadline time), by priority, by TODO keyword or by the value of a property.

Ctrl-c ^org-sortsorts the selected region

export

<Ctrl-c> <Ctrl-e>export/publish dispatcher

time tracking

C-c C-x C-i(org-clock-in)Start the clock on the current item
C-c C-x C-o(org-clock-out)Stop the clock
C-c C-x C-x(org-clock-in-last)Reclock the last clocked task
C-c C-x C-r(org-clock-report)Show a report table
C-c C-x C-dorg-clock-displaySummarize times inline

workgroups2

<Ctrl-c> z<prefix>
<prefix> ccreate workgroup
<prefix> Arename workgroup
<prefix> kkill workgroup
<prefix> vswitch to workgroup
<prefix> C-ssave session
<prefix> C-fload session

helm

usage

You can mark candidates with C-SPC; this is useful when you need to perform an action on many candidates of your choice (kill buffers for example). M-a to select all. You can insert marked candidates into the current buffer with C-c C-i. This is useful when you have narrowed to a list of candidates, i.e. files, and then you want to save such candidates. If you find the current horizontal Helm window is small, you can always switch it to a vertical window with C-t. Running C-t again returns the Helm window back to horizontal and so on.

From within a helm-find-files session, you can invoke helm-ff-run-grep with C-s to search a file/directory on highlighted entry in the Helm buffer. With prefix argument C-u, recursively greps a selected directory.

You can also save the result into a Grep buffer using the action Save results in Grep buffer. Note that this Grep buffer is created by Helm, not the default Emacs grep buffer. It has minimal key bindings. In hgrep buffer, press C-h m to view all key bindings.

functions

helm-for-files
helm-complex-command-history
helm-projectile-grep
helm-info
helm-find
helm-info
helm-regexp
helm-top
helm-surfraw
helm-color
helm-eval-expression-with-eldoc
helm-calcul-expression
helm-show-kill-ring
helm-find-fileslike find-file-at-point

magit

<Meta-x> magit-statusshow magit status buffer
sStage current hunk
uUnstage current hunk
SStage all hunks
UUnstage all hunks
kDiscard uncommitted changes
cPrepare for commit
C-c C-cExecute commit triggers commit action
C-c C-aMake the next commit an amend

smartparens

sp-splice-sexpremove surrounding

git

undo

undo last commit

git reset HEAD~

# If you don't want the changes and blow everything away:
git reset --hard HEAD~

undo added file

git checkout file

moving to a new branch

move commits to a new branch

# Note: Any changes not committed will be lost.
git branch newbranch      # Create a new branch, saving the desired commits
git reset --hard HEAD~3   # Move master back by 3 commits (GONE from master)
git checkout newbranch    # Go to the new branch that still has the desired commits

But do make sure how many commits to go back. Alternatively, you can instead of HEAD~3, simply provide the hash of the commit (or the reference like origin/master) you want to “revert back to” on the master (/current) branch, e.g:

git reset --hard a1b2c3d4

*1 You will only be “losing” commits from the master branch, but don’t worry, you’ll have those commits in newbranch!

moving to an existing branch

WARNING The method above works because you are creating a new branch with the first command: git branch newbranch. If you want to use an existing branch you need to merge your changes into the existing branch before executing git reset –hard HEAD~3. If you don’t merge your changes first, they will be lost. So, if you are working with an existing branch it will look like this:

git checkout existingbranch
git merge master
git checkout master
git reset --hard HEAD~3 # Go back 3 commits. You *will* lose uncommitted work.
git checkout existingbranch

general

reference the last branch

git checkout -

remove all deleted files

git rm $(git ls-files --deleted)

add changes to the last commit

git commit --amend

add partial

git add --partial
# git add -p
git gui

ancestry references

ref~

Shorthand for ref~1 and means the commit’s first parent. ref~2 means the commit’s first parent’s first parent. ref~3 means the commit’s first parent’s first parent’s first parent. And so on.

ref^

Shorthand for ref^1 and means the commit’s first parent. But where the two differ is that ref^2 means the commit’s second parent (remember, commits can have two parents when they are a merge).

combined

The ^ and ~ operators can be combined.

example

HEAD                -> *     5. commit on master
HEAD~1 or HEAD^1    -> *     Merge branch 'my_branch'
                       |\
HEAD~1^2            -> | *   1. commit on branch
HEAD~2 or HEAD~1^1  -> * /   4. commit on master
HEAD~3 or HEAD~2^1  -> *     3. commit on master
etc...                 *     2. commit on master
                       *     1. commit on master

grep in git history

git grep <regexp> $(git rev-list --all)
# or
git rev-list --all | xargs git grep expression

force overwrite pull

git fetch --all
git reset --hard origin/master

delete a tag

git tag -d <tagname>
git push origin :refs/tags/<tagname>

delete a branch

git push origin --delete <branchName>

show merge status of a branch

git branch --merged
git branch --no-merged

show the entire history of the file (including history beyond renames and with diffs for each change).

git log --follow -p -- filename

show logs of today in a compact view

git log --since="yesterday" --pretty="oneline"

stash (useful too, when working on the wrong branch)

git stash
git stash apply

show staged diffs

git diff --cached

show diffs between two commits

git diff <commit-id>..<commit-id>
git diff <tag-name || branch-name> <file>

export

git archive <branch-name> --format=zip --output=<file>

push local branch

git push -u origin feature_branch_name

show commits in a time interval

git log --after="2015-11-13 00:00" --before="2015-11-16 23:59"

git flow

create a feature branch

git checkout -b myfeature develop

finishing a feature branch

git checkout develop
git merge --no-ff myfeature
git branch -d myfeature
git push origin develop

creating a release branch

git checkout -b release-1.2 develop
git commit -a -m "Bumped version number to 1.2"

finishing a release branch

git checkout master
git merge --no-ff release-1.2
git tag -a 1.2

git checkout develop
git merge --no-ff release-1.2

git branch -d release-1.2

var QueryString = function () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! var query_string = {}; var query = window.location.search.substring(1); var vars = query.split(“&”); for (var i=0;i<vars.length;i++) { var pair = vars[i].split(“=”); // If first entry with this name if (typeof query_string[pair[0]] === “undefined”) { query_string[pair[0]] = decodeURIComponent(pair[1]); // If second entry with this name } else if (typeof query_string[pair[0]] === “string”) { var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(decodeURIComponent(pair[1])); } } return query_string; }();

macOS

Finder

<Cmd><Shift>Gopen directory path

input

<Ctrl><Cmd><SPC>open emoji keyboard

Windowmanager

<Cmd><F3>show desktop

python

set operations

debugging

functions

https://docs.python.org/3/howto/functional.html

params, kwargs…

attrgetter

partial

methodcaller

modern replacements for map, reduce… 148

sorting

by aspect

from operator import itemgetter

metro_data = [('Tokyo', 'JP'), ('Delhi NCR', 'IN')]
for city in sorted(metro_data, key=itemgetter(1)):
    print(city)

control structures

for

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    # case no-break
    else:
        return -1
    return i

special methods

https://docs.python.org/3/reference/datamodel.html#special-method-names

import collections

Card = collections.namedtuple('Card', ['rank', 'suit'])

class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits
                                        for rank in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]

    deck = FrenchDeck()
    deck[0]            # list like access
    # start, stop, step
    deck[12::13]       # slicing the aces
    for card in deck:  # iterable (also for reverse())
        print(card)
    from random import choice
    choice(deck)       # no need for custom random card function

squences

string

reverse

'hello world'[::-1]

tuple

unpacking

named tuple

Class that bundles some attributes without custom methods (like a struct).

import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
# or
Card = collections.namedtuple('Card', 'rank suit')

named slice

price_summary = 'EUR 9,99'
currency_slice = slice(0, 3)
price_slice = slice(4, None)
currency = price_summary[currency_slice]
price = price_summary[price_slice]

array

list

[].sort

key

sorted([])

bisect

bisect

insort

collections

dequeue

requests

dump html file

html = requests.get('https://example.com/')
def dump_html(html):
    with open('dump.html', 'wb') as file:
        for block in html.iter_content(1024):
            file.write(block)

openpyxl

from openpyxl import Workbook

data = [
        ['sheet-one-foo-data', 'sheet-one-bar-data']
        ['sheet-two-foo-data', 'sheet-two-bar-data']
       ]

wb = Workbook()
for sheet_idx, elem in enumerate(data):
    sheet_name = 'sheet-{}'.format(sheet_idx + 1)
    wb.create_sheet(sheet_name)
    header = ['foo', 'bar']
    wb[sheet_name].append(header)
    for row in elem:
        wb[sheet_name].append(elem)

del wb['Sheet']
wb.save(filename='excel.xlsx')

SQL

find duplicated values

SELECT
    address_line1, address_line2, zip, city, country, COUNT(*)
FROM
    location
GROUP BY
    address_line1, address_line2, zip, city, country
HAVING
    COUNT(*) > 1;

show the average length of a column

SELECT
    AVG(LENGTH(column1))
FROM table1

reset AUTO_INCREMENT

ALTER TABLE tablename AUTO_INCREMENT = 1

shell tools

ag

include files in the search that matches a pattern

ag -G pattern searchterm

awk

print all columns but the first

awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}'

print all columns but the first 3

awk '{ $1=""; $2=""; $3=""; print $0 }'

use a regex as a field separator awk

awk -F '[0-9][0-9]' '{print $2}'

remove duplicate lines whilst keeping empty lines and order

awk '!NF || !seen[$0]++'

swap two columns

awk ' { t = $1; $1 = $2; $2 = t; print; } ' input_file

cut

cut from character 4 to the end

cut -c 4-

diff

diff sorted

diff <(sort file_a) <(sort file_b)

diff folders

diff -qr /path/to/folder1 /path/to/folder2

less

better tail -f

less +F

help

<h>

sed

delete lines containing pattern

sed '/<pattern>/d' file

delete lines not containing pattern a or b

sed '/<a>\|<b>/!d' file

delete all occurences of pattern

sed 's/<pattern>//g'

print the lines between two line numbers

sed -n '5,10p' <filename>

delete leading whitespace (spaces, tabs) from front of each line aligns all text flush left

sed 's/^[ \t]*//'

delete trailing whitespace (spaces, tabs) from end of each line

sed 's/[ \t]*$//'

delete BOTH leading and trailing whitespace from each line

sed 's/^[ \t]*//;s/[ \t]*$//'

delete lines longer than 15 chars

sed '/.\{16\}/d'

print only lines which match regular expression (emulates “grep”)

sed -n '/regexp/p'           # method 1
sed '/regexp/!d'             # method 2

print only lines which do NOT match regexp (emulates “grep -v”)

sed -n '/regexp/!p'          # method 1, corresponds to above
sed '/regexp/d'              # method 2, simpler syntax

substitute (find and replace) “foo” with “bar” on each line

sed -i.bak 's/foo/bar/g' file.txt    # make the changes inline and create a backup of the original file before it does the changes in-place
sed 's/foo/bar/'             # replaces only 1st instance in a line
sed 's/foo/bar/4'            # replaces only 4th instance in a line
sed 's/foo/bar/g'            # replaces ALL instances in a line
sed 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
sed 's/\(.*\)foo/\1bar/'            # replace only the last case

substitute “foo” with “bar” ONLY for lines which contain “baz”

sed '/baz/s/foo/bar/g'

substitute “foo” with “bar” EXCEPT for lines which contain “baz”

sed '/baz/!s/foo/bar/g'

change “scarlet” or “ruby” or “puce” to “red”

sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g'   # most seds
gsed 's/scarlet\|ruby\|puce/red/g'                # GNU sed only

reverse order of lines (emulates “tac”)

# bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d'               # method 1
sed -n '1!G;h;$p'             # method 2

# reverse each character on the line (emulates "rev")
sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

join pairs of lines side-by-side (like “paste”)

sed '$!N;s/\n/ /'

# if a line ends with a backslash, append the next line to it
sed -e :a -e '/\\$/N; s/\\\n//; ta'

# add commas to numeric strings, changing "1234567" to "1,234,567"
gsed ':a;s/\B[0-9]\{3\}\>/,&/;ta'                     # GNU sed
sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'  # other seds

# add commas to numbers with decimal points and minus signs (GNU sed)
gsed ':a;s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta'

remove leading whitespace and tabs

sed -e 's/^[ \t]*//'

remove trailing whitespace and tabs

sed 's/[ \t]*$//'

remove leading and trailing whitespace and tabs

sed 's/^[ \t]*//;s/[ \t]*$//'

edit inplace

# file.bak is the backup; file will be edited
sed -i .bak "/<pattern>/d" file

tail

reverse

tail -r

skip first line

tail +2

wc

count lines in file

wc -l < file|bc

count occurrences

grep -o "needle" file | wc -l

imagemagick

convert

filetype

convert image.jpg newimage.png

layered file

convert -flatten image.psd newimage.jpg

crop

#                       size xy offset xy
convert image.png -crop 980x880+950+630 newimage.png

diff

compare -compose src file-a.jpg file-b.jpg difference.png

docker

cleanup

kill all running containers

docker kill $(docker ps -q)

delete all stopped containers (including data-only containers)

docker rm $(docker ps -a -q)

delete all ‘untagged/dangling’ (<none>) images

docker rmi $(docker images -q -f dangling=true)

delete ALL images

docker rmi $(docker images -q)

wget

download directory

# avoid downloading the index.html files
    wget -r --no-parent --reject "index.html*" http://example.com/dir

tar

compress directory

tar -zcvf archive-name.tar.gz directory-name

pip

upgrade all packages

pip freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U

pbpaste

paste plain text

pbpaste | textutil -convert txt -stdin -stdout -encoding 30 | pbcopy

ranger

Edit the current file in $EDITOR (“nano” by default)E
Open a shell in the current directoryS

vim

search and replace

:range s[ubstitute]/pattern/string/cgiI

metacharacters

.any character except new line  
\swhitespace character\Snon-whitespace character
\ddigit\Dnon-digit
\xhex digit\Xnon-hex digit
\ooctal digit\Onon-octal digit
\hhead of word character (a,b,c…z,A,B,C…Z and _)\Hnon-head of word character
\pprintable character\Plike \p, but excluding digits
\wword character\Wnon-word character
\aalphabetic character\Anon-alphabetic character
\llowercase character\Lnon-lowercase character
\uuppercase character\Unon-uppercase character

modifiers

cConfirm each substitution
gReplace all occurrences in the line (without g - only first).
iIgnore case for the pattern.
IDon’t ignore case for the pattern.

range

numberan absolute line number
.the current line
$the last line in the file
%the whole file. The same as 1,$
‘tposition of mark “t”
/pattern[/]the next line where text “pattern” matches.
?pattern[?]the previous line where text “pattern” matches
\/the next line where the previously used search pattern matches
\?the previous line where the previously used search pattern matches
\&the next line where the previously used substitute pattern matches

quantifiers

n and m are positive integers (>0)

greedy

*matches 0 or more of the preceding characters, ranges or metacharacters .* matches everything including empty line
\+matches 1 or more of the preceding characters…
\=matches 0 or 1 more of the preceding characters…
\{n,m}matches from n to m of the preceding characters…
\{n}matches exactly n times of the preceding characters…
\{,m}matches at most m (from 0 to m) of the preceding characters…
\{n,}matches at least n of of the preceding characters…

non greedy

\{-}matches 0 or more of the preceding atom, as few as possible
\{-n,m}matches 1 or more of the preceding characters…
\{-n,}matches at lease or more of the preceding characters…
\{-,m}matches 1 or more of the preceding characters…

grouping

&the whole matched pattern
\Lthe following characters are made lowercase
\0the whole matched pattern
\Uthe following characters are made uppercase
\1the matched pattern in the first pair of \(\)
\Eend of \U and \L
\2the matched pattern in the second pair of \(\)
\eend of \U and \L
\rsplit line in two at this point
\9the matched pattern in the ninth pair of \(\)
\lnext character made lowercase
~the previous substitute string
\unext character made uppercase

remove duplicate lines

:g/^\(.*\)\n\1$/d

sort unique

:sort u

delete

In Normal mode:

dawdelete word under cursor
cawdelete word under cursor, go in insert mode
df<char>delete all the chars until (and including) the next <char>
Ddelete the characters under the cursor until the end of the line
ccchange (replace) an entire line
cwchange (replace) to the end of word
c$change (replace) to the end of line

search editor

<q-/>open search editor

highlight duplicate lines

:syn clear Repeat | g/^\(.*\)\n\ze\%(.*\n\)*\1$/exe 'syn match Repeat "^' . escape(getline('.'), '".\^$*[]') . '$"' | nohlsearch

replace ’ ’ with new line (\n)

:%s/ /<ctrl-v><enter>/g
or
:%s/ /\r/g

substitute umlauts with html entities

:%s/ü/\&uuml;/eg | :%s/ä/\&auml;/eg | :%s/ö/\&ouml;/eg | :%s/ß/\&szlig;/eg | :%s/Ü/\&Uuml;/eg | :%s/Ä/\&Auml;/eg | :%s/Ö/\&Ouml;/eg

count occcurrences of pattern

:%s/pattern//gn

delete empty/whitespace lines

:g/^\s*$/d

delete negated

:g!/python/d

or

:v/python/d

delete combined

:v/error\|warn\|fail/d

delete lines not containing pattern

:v/pattern/d

substitute whitespace between numbers

:%s/\([0-9]\)\s\([0-9]\)/\1\2/g

append , to the end of every line

:%s/$/\,/g

substitute ^M linebreaks with normal linebreaks

:%s/\r/\r/g

remove datestamp in a python logfile

:%s/\d\{4}-\d\{2}-\d\{2} \d\{2}\:\d\{2}:\d\{2},\d\{3} //g

remove blank lines

:g/^$/d

groups

:%s /\(the group\)/this is \1/g

general

<Ctrl-a>increase the number under the cursor (in normal mode)
<Ctrl-x>decrease the number under the cursor (in normal mode)

movement

H(H)igh: Jump to the top of the screen
M(M)iddle: Jump to the middle of the screen
L(L)ow: Jump to the boottom of the screen
e(e)nd: Jump to the end of a word
wJump to be beginning of a word
WMove forward a WORD (any non-whitespace characters)
bMove backward to the beginning of a word
)Jump forward one sentence
(Jump backward one sentence
}Jump forward one paragraph
{Jump backward one paragraph
Return to the line where the cursor was before the latest jump (Two single quotes.)
Return to the cursor position before the latest jump (undo the jump) (Two back ticks. This is above the Tab key on some keyboards.)
’.Jump to the last-changed line.
%Jump to corresponding item, e.g. from an open brace to its matching closing brace. See Moving to matching braces for more.
gigoto last insert
<Ctrl-o>jump to last (older) cursor position
<Ctrl-i>jump to next cursor position

YouCompleteMe

<Leader>ydGo to declarationYcmCompleter GoToDeclaration
<Leader>ygGo to declaration / referenceYcmCompleter GoTo
<Leader>yrGo to referenceYcmCompleter GoToReferences
<Leader>yDGet documentationGetDoc

commandline

diff file1 and file2 in splitpanes

vim -d file1 file2

open file in a new tab

vim --remote-tab-silent

splits

max out the height of the current split

ctrl + w _

max out the width of the current split

ctrl + w |

normalize all split sizes, which is very handy when resizing terminal

ctrl + w =

swap top/bottom or left/right split

Ctrl+W R

tabs

break out current window into a new tabview

Ctrl+W T

close every window in the current tabview but the current one

Ctrl+W o

formatting

indent line

=

fix file indentation

gg=G
:retab

more

get information about visual selection

g C-g

print keycode

i <ctrl> k <key>

show linebreaks

:set listchars=eol:$,tab:\ \ 

count occurences of a pattern

:%s/pattern//gn

spelling

:setlocal spell spelllang=en_us
:setlocal spell spelllang=de_de
:set nospell

command history

q:

search history

q/

zsh

misc

shebang

#!/usr/bin/env bash

dryrun

sh -e

here document

cat <<LimitString
foo
bar
baz
LimitString

write on top of a file

echo -e "first line\n$(cat file.txt)" > file.txt

jump to a directory, execute a command and jump back to current dir

(cd /tmp && ls)

avoid cat abuse

~~cat filename | sort~~
sort < filename

create a directory and cd into it

mkdir /home/foo/doc/bar && cd $_

prefix all files in the current directory

# zsh
for file in *; do
    mv $file prefix_${file%%}
done
# bash
for file in *; do
    mv $file prefix_"${file%.*}"
done

check if an item is in an array

item_in () {
    local item
    for item in "${@:2}"; do [[ "$item" == "$1" ]] && return 0; done
    return 1
}

# $ array=("something to search for" "a string" "test2000")
# $ item_in "a string" "${array[@]}"
# $ echo $?
# 0
# $ containsElement "foo" "${array[@]}"
# $ echo $?
# 1

replace in filename

replace - by _ in pwd

for file in *; do mv $file ${file/-/_} ; done

# or with tr
ls | while read -r file
do
    mv -v "$file" `echo $file | tr '-' '_'`
done

# or with rename
rename '-' '_' *

create a string with $n*$char

n=42
char="-"
spacer=$(head -c $n < /dev/zero | tr '\0' "$char")

redirection

cmdfunction
prog > filesend stdout to file
prog 2> filesend stderr to file
prog > file 2>&1send stdout and stderr to file
prog < filetake stdin from file
prog >> filesend stdout to end of file
prog 2>> filesend stderr to end of file
prog >> file 2>&1send stdout and stderr to end fo file
prog <<cread stdin from keyboard until c
prog | prog2pipe stdout to prog2
prog 2>&1 | prog2pipe stdout and stderr to prog2
prog > /dev/null 2>&1redirect stdout, stderr
prog 2> /dev/nulredirect stderr
prog &> /dev/nullredirect stdout

job control

suspend a job running in foreground

<ctrl-z>

start a job in background

gcc program.c -o program &

list background jobs

jobs

bring the background job with the job id 1 to foreground

fg %1

terminate the background job with the job id 1

kill %1

keybindings

keydescription
<escape-.>last param of the last command (repeat)
<ctrl-u> […] <ctrl-y>type partial command, kill this command, check something you forgot, yank the command, resume typing
<alt-.>insert previous command argument
<alt-a>multiselect in menu complete
<alt-arrow-left>move a word backward
<alt-arrow-right>move a word forward
<cmd-del>delete the word left of the cursor
<cmd-arrow-left>move to the beginning of the line
<cmd-arrow-right>move to the end of the line
<cmd-arrow-down>delete the whole line
<ctrl-x>delete the char under the cursor
<ctrl-w>delete the word under the cursor
<alt-arrow-up>cd ..
<ctr-l>ls -laH
<arrow-up>history substring search backward
<arrow-down>history substring search forward
<ctrl-z>suspend job to background

globbing

list all javascript files under pwd

ls **/**js

list text files that end in a number from 1 to 10

ls -l zsh_demo/**/*<1-10>.txt

list text files that start with the letter a

ls -l zsh_demo/**/[a]*.txt

list text files that start with either ab or bc

ls -l zsh_demo/**/(ab|bc)*.txt

list text files that don’t start with a lower or uppercase c

ls -l zsh_demo/**/[^cC]*.txt

show only directories

print -l zsh_demo/**/*(/)

show only regular files

print -l zsh_demo/**/*(.)

show empty files

ls -l zsh_demo/**/*(L0)

show files greater than 3 KB

ls -l zsh_demo/**/*(Lk+3)

show files modified in the last hour

print -l zsh_demo/**/*(mh-1)

sort files from most to least recently modified and show the last 3

ls -l zsh_demo/**/*(om[1,3])

expansion

parameter expansion

git diff ./file_1.py
git add !:2<TAB>            * expands to git add ./file_1.py

!!                          * last command
!$                          * last parameter of the last command
!*                          * all parameters

parameter processing

one by one
*!/bin/bash

for i in "$@"
do
    case $i in
        -e=*|--extension=*)
            EXTENSION="${i**=}"
            shift * past argument=value
            ;;
        -s=*|--searchpath=*)
            SEARCHPATH="${i**=}"
            shift * past argument=value
            ;;
        -l=*|--lib=*)
            LIBPATH="${i**=}"
            shift * past argument=value
            ;;
        --default)
            DEFAULT=YES
            shift * past argument with no value
            ;;
        *)
            * unknown option
        ;;
    esac
done
paired
    #!/bin/bash
    # Use -gt 1 to consume two arguments per pass in the loop (e.g. each
    # argument has a corresponding value to go with it).
    # Use -gt 0 to consume one or more arguments per pass in the loop (e.g.
    # some arguments don't have a corresponding value to go with it such
    # as in the --default example).
    # note: if this is set to -gt 0 the /etc/hosts part is not recognized ( may be a bug )
    while [[ $* -gt 1 ]]
    do
        key="$1"

        case $key in
            -e|--extension)
                EXTENSION="$2"
                shift * past argument
                ;;
            -s|--searchpath)
                SEARCHPATH="$2"
                shift * past argument
                ;;
            -l|--lib)
                LIBPATH="$2"
                shift * past argument
                ;;
            --default)
                DEFAULT=YES
                ;;
            *)
                * unknown option
            ;;
        esac
    shift * past argument or value
done
reverse
files=(/var/logs/foo*.log)
   for ((i=${*files[@]}-1; i>=0; i--)); do
     bar "${files[$i]}"
   done

OS X

use mac apps from the shell

open -a /Applications/Whatever.app

prevent spotlight from indexing external volume

mdutil -i off /Volumes/VolumeName

locatemd: to search for a file using Spotlight’s metadata

spotlight $file

show the SpotLight comment for a file

spotlight_comment $file

oh my zsh

return the current Finder selection

pfs

cd to the current Finder directory

cdf

quick look a specified file

quick-look $file

eject all external volumes

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