Development and scripting encompass the tools and languages used to write, edit, and manage code. This category includes editors, programming languages, and version control systems, all of which are essential for software development, automation, and collaboration.
Development tools are essential for creating, editing, and managing software applications and scripts. They encompass a wide range of applications, including text editors, integrated development environments (IDEs), and debugging tools. Text editors provide a simple interface for writing code, while IDEs offer advanced features like code completion, syntax highlighting, and integrated debugging.
Programming languages are a core component of development tools, enabling developers to write instructions that computers can execute. Each language has its own syntax and use cases, from web development to system programming. Version control systems are another critical aspect, allowing developers to track changes, collaborate on projects, and manage different versions of code.
Development tools also include build automation tools, which streamline the process of compiling and deploying code. Testing frameworks are used to ensure that software functions correctly and meets quality standards. Additionally, package managers help developers manage libraries and dependencies, simplifying the process of adding new functionality to projects.
Overall, development tools enhance productivity, improve code quality, and facilitate collaboration among developers. They are indispensable for modern software development, enabling teams to build, test, and deploy applications efficiently.
1.1 - 🖥️case
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the case command with important options and switches using examples.
# ██████╗ █████╗ ███████╗███████╗# ██╔════╝██╔══██╗██╔════╝██╔════╝# ██║ ███████║███████╗█████╗ # ██║ ██╔══██║╚════██║██╔══╝ # ╚██████╗██║ ██║███████║███████╗# ╚═════╝╚═╝ ╚═╝╚══════╝╚══════╝syntax of bash case statement.
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
...
esac#!/bin/bashecho "enter the value"read a
case$a in
1) echo ” 1 ” ;&
2) echo ” 2 ” ;&
3) echo ” 3 ” ;;&
4) echo ” 4 ” ;;
5) echo ” 5 ” ;&
esac# Example 01#------------##!/bin/bash# signal.shif [ $# -lt 2 ]
then echo "Usage : $0 Signalnumber PID" exit
ficase"$1" in
1) echo "Sending SIGHUP signal" kill -SIGHUP $2 ;;
2) echo "Sending SIGINT signal" kill -SIGINT $2 ;;
3) echo "Sending SIGQUIT signal" kill -SIGQUIT $2 ;;
9) echo "Sending SIGKILL signal" kill -SIGKILL $2 ;;
*) echo "Signal number $1 is not processed" ;;
esac# Example 02 - Pattern Match in a File#--------------------------------------##!/bin/bash# fileop.sh# Check 3 arguments are given #if [ $# -lt 3 ]
then echo "Usage : $0 option pattern filename" exit
fi# Check the given file is exist #if [ ! -f $3 ]
then echo "Filename given \"$3\" doesn't exist" exit
ficase"$1" in
# Count number of lines matches-i) echo "Number of lines matches with the pattern $2 :" grep -c -i $2$3 ;;
# Count number of words matches-c) echo "Number of words matches with the pattern $2 :" grep -o -i $2$3 | wc -l
;;
# print all the matched lines-p) echo "Lines matches with the pattern $2 :" grep -i $2$3 ;;
# Delete all the lines matches with the pattern-d) echo "After deleting the lines matches with the pattern $2 :" sed -n "/$2/!p"$3 ;;
*) echo "Invalid option" ;;
esac# Execution of the above script is shown below. $ cat text
Vim is a text editor released by Bram Moolenaar in 1991for the Amiga computer.
The name "Vim" is an acronym for"Vi IMproved" because Vim was created as an extended version of the vi editor, with many additional features designed to be helpful in editing program source code.
Although Vim was originally released for the Amiga, Vim has since been developed to be cross-platform, supporting many other platforms.
It is the most popular editor amongst Linux Journal readers.
Bash case regex output. After deleting the lines matches with the pattern Vim:
$ ./fileop.sh -d Vim text
It is the most popular editor amongst Linux Journal readers.
# Example 03 - Find File type from the Extension#------------------------------------------------##!/bin/bash# filetype.shfor filename in $(ls)do# Take extension available in a filenameext=${filename##*\.}case"$ext" in
c) echo "$filename : C source file" ;;
o) echo "$filename : Object file" ;;
sh) echo "$filename : Shell script" ;;
txt) echo "$filename : Text file" ;;
*) echo " $filename : Not processed" ;;
esacdone $ ./filetype.sh
a.c : C source file
b.c : C source file
c1.txt : Text file
fileop.sh : Shell script
obj.o : Object file
text : Not processed
t.o : Object file
# Example 04 - Prompt User with Yes or No#-----------------------------------------##!/bin/bash# yorno.shecho -n "Do you agree with this? [yes or no]: "read yno
case$yno in
[yY] | [yY][Ee][Ss] )
echo "Agreed" ;;
[nN] | [n|N][O|o] )
echo "Not agreed, you can't proceed the installation";
exit 1 ;;
*) echo "Invalid input" ;;
esac $ ./yorno.sh
Do you agree with this? [yes or no]: YES
Agreed
# Example 05 - Startup script#-----------------------------------------##!/bin/bash# startpcapp.shcase"$1" in
'start')
echo "Starting application"/usr/bin/startpc
;;
'stop')
echo "Stopping application"/usr/bin/stoppc
;;
'restart')
echo "Usage: $0 [start|stop]";;
esac $ ./startpcapp start
Starting application
/usr/bin/startpc started
#!/bin/sh# talk.sh from https://www.shellscript.sh/case.htmlecho "Please talk to me ..."while :
do read INPUT_STRING
case$INPUT_STRING in
hello)
echo "Hello yourself!" ;;
bye)
echo "See you again!" break
;;
*)
echo "Sorry, I don't understand" ;;
esacdoneecho
echo "That's all folks!" Okay, so it's not the best conversationalist in the world; it's only an example!
Try running it and check how it works...
$ ./talk.sh
Please talk to me ...
hello
Hello yourself!
What do you think of politics?
Sorry, I don't understand
bye
See you again!
That's all folks!
$
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command case in a clear format. This allows users to quickly access the needed information for case without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for case are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the for command with important options and switches using examples.
# ███████╗ ██████╗ ██████╗ # ██╔════╝██╔═══██╗██╔══██╗# █████╗ ██║ ██║██████╔╝# ██╔══╝ ██║ ██║██╔══██╗# ██║ ╚██████╔╝██║ ██║# ╚═╝ ╚═════╝ ╚═╝ ╚═╝# basic loopfor i in 12345678910do echo $idone# loop ls command resultsfor var in `ls -alF`do echo $vardone# loop specified number of timesfor i in `seq 1 10`do echo $idone#==============================##==============================## CMD FOR for-schleife ##==============================##==============================#for i in one two three ; do printf "'$i'," ; done | sed 's/,$//' ; echo
# Prepare a list of items (one two three) for SQL list syntax.for i in *.jpg; do identify "$i"; done# Use a for loop to iterate over a list of items (files, numbers, etc) and run processes accordingly.for i in {1..20} ; do rig|head -1 |tr A-Z a-z;done |while read f l;do echo ${f:0:1}${l}:$(pwgen 12 1);done# Gen 20 random users/passwordsfor file in * ; do echo mv "$file""`echo $file | tr [:upper:] [:lower:]`"; done# To give an example this can be used to rename all files in the current directory to lowercase (there are other ways to do this, but this is a decent example) -> Of course you can convert the other way by swapping '[:upper:]' and '[:lower:]'.for dir in */ ; do echo "${dir%/}" ; done# Use the */ trick to get only the directories, then use ${dir%/} to remove the trailing / you getfor p in *.tiff; do convert -quality 75 -scale 50% "$p""${p%%.tiff}.jpg"; echo converted $p; done# Convert tiff images to rescaled jpgfor w in {1..104} ; do date -d "now - $w weeks" +%Y-%m-%d ; done# Last 2 years of this weekday. Shorter easier to read version. ;-)for t in "Wake up""The Matrix has you""Follow the white rabbit""Knock, knock";do pv -qL10 <<<$'\e[2J'$'\e[32m'$t$'\e[37m';sleep 5;donefor i in $(ls -1 /usr/share/man/man1/) ; dop=${i//.1.gz} ; echo -n "$p " ; man $p|egrep "^[\ \t]*--?[a-zA-Z0-9]"|wc -l;done# option countfor n in 3041413841999931 30;dofor t in {0..2200};do [[ $(($t%$n)) == 0 ]]&&echo -n $'\xb0'||echo -n $'\x80';done;done>/dev/dsp
# sndfor d in */; do echo -n "$d "; file -b "$d"/* |cut -d' ' -f1 |sort| uniq -c| sort -rn|head -1; done# Most common type of file per subdir.for x in -{630..599}; dofor z in -{115..130}; do echo "/setblock $x 60 $z minecraft:stone";done;done# Minecraft make stone floor commands.for i in {1..10} ; do sleep $(($RANDOM % 3600 + 1800)) ; twitter-queueposter.py ; done# Engage lazy mode.for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300$i thumbs/$i ; done# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPGfor i in 172.16.0.{1..254};do (ping -c1 $i > /dev/null && echo $_) &done > pinged-hosts
# Quickly scan network without using nmap, etc.for p in *.jpg; do ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi; done# Make slideshow from *.jpgfor f in *; dob=$(echo "$f" | tr '[A-Z]''[a-z]'); mv "$f""$b"; done# Lower case all files in a folder.for f in *.mp4; do echo "processing $f"; bname=$(basename $f); ffmpeg -i "$f""$bname.wav"; done# Convert MP4 to WAV. for d in */; do echo $d; cd $d; npm outdate; cd - > /dev/null; done# NPM outdate for projects in dir. for i in *.jpg; do identify "$i"; done# Use a for loop to iterate over a list of items (files, numbers, etc) and run processes accordingly.for i in {1..20} ; do rig|head -1 |tr A-Z a-z;done |while read f l;do echo ${f:0:1}${l}:$(pwgen 12 1);done# Gen 20 random users/passwordsfor file in * ; do echo mv "$file""`echo $file | tr [:upper:] [:lower:]`"; done# To give an example this can be used to rename all files in the current directory to lowercase (there are other ways to do this, but this is a decent example) -> # Of course you can convert the other way by swapping '[:upper:]' and '[:lower:]'.for dir in */ ; do echo "${dir%/}" ; done# Use the */ trick to get only the directories, then use ${dir%/} to remove the trailing / you getfor i in *.jpg;do printf "$i %s\n"$(convert "$i" -scale 1x1\! -format '%[pixel:u]' info:- ) ;done |tee -a color-indexes.txt
# Major colorsfor x in $(docker images | awk '$1 ~ "<none>" {print $3}'); do docker rmi $x; done# Deletes orphaned docker images. for d in */; do echo $d; cd $d; npm outdate; cd - > /dev/null; done# NPM outdate for projects in dir. for f in *.mp4; do echo "processing $f"; bname=$(basename $f); ffmpeg -i "$f""$bname.wav"; done# Convert MP4 to WAV. for i in one two three ; do printf "'$i'," ; done | sed 's/,$//' ; echo
# Prepare a list of items (one two three) for SQL list syntax.for i in {1..254}; do ping -c 1 -W 1 10.1.1.$i | grep 'from'; done#Ping scanning without nmap#Usefull for when you don't have nmap and need to find a missing host.#Pings all addresses from 10.1.1.1 to 10.1.1.254, modify for your subnet.#Timeout set to 1 sec for speed, if running over a slow connection you should raise that to avoid missing replies.#This will clean up the junk, leaving just the IP address:for i in {1..254}; do ping -c 1 -W 1 10.1.1.$i | grep 'from' | cut -d' ' -f 4 | tr -d ':'; donefor i in $(seq 4 65);do echo -n "${pi:0:$i}.com: ";whois ${pi:2:$((i-2))}.com|grep --col=no "rant Na"||echo;sleep 5;done#pi domain ownersfor i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300$i thumbs/$i ; done# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPG# Right, so you will probably want to use 3[0-4]??.JPG or 3[0-4][0-9][0-9].JPG to be more precise.for x in $(docker images | awk '$1 ~ "<none>" {print $3}'); do docker rmi $x; done# Deletes orphaned docker images. for i in *.jpg;do printf "$i %s\n"$(convert "$i" -scale 1x1\! -format '%[pixel:u]' info:- ) ;done |tee -a color-indexes.txt
# Major colorsfor i in {1..20} ; do rig|head -1 |tr A-Z a-z;done |while read f l;do echo ${f:0:1}${l}:$(pwgen 12 1);done# Gen 20 random users/passwordsfor i in *.jpg; do identify "$i"; done# Use a for loop to iterate over a list of items (files, numbers, etc) and run processes accordingly.for i in $(seq 4 65);do echo -n "${pi:0:$i}.com: ";whois ${pi:2:$((i-2))}.com|grep --col=no "rant Na"||echo;sleep 5;done#pi domain ownersfor f in *; dob=$(echo "$f" | tr '[A-Z]''[a-z]'); mv "$f""$b"; done# Lower case all files in a folder.for dir in */ ; do echo "${dir%/}" ; done# Use the */ trick to get only the directories, then use ${dir%/} to remove the trailing / you getfor i in 172.16.0.{1..254};do (ping -c1 $i > /dev/null && echo $_) &done > pinged-hosts
# Quickly scan network without using nmap, etc.for p in *.jpg; do ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi; done# Make slideshow from *.jpgfor i in {1..10} ; do sleep $(($RANDOM % 3600 + 1800)) ; twitter-queueposter.py ; done# Engage lazy mode.for x in -{630..599}; dofor z in -{115..130}; do echo "/setblock $x 60 $z minecraft:stone";done;done#Minecraft make stone floor commands.#for p in *.tiff; do convert -quality 75 -scale 50% "$p""${p%%.tiff}.jpg"; echo converted $p; done# Convert tiff images to rescaled jpgfor d in */; do echo -n "$d "; file -b "$d"/* |cut -d' ' -f1 |sort| uniq -c| sort -rn|head -1; done# Most common type of file per subdir.for n in 3041413841999931 30;dofor t in {0..2200};do [[ $(($t%$n)) == 0 ]]&&echo -n $'\xb0'||echo -n $'\x80';done;done>/dev/dsp
# sndfor t in "Wake up""The Matrix has you""Follow the white rabbit""Knock, knock";do pv -qL10 <<<$'\e[2J'$'\e[32m'$t$'\e[37m';sleep 5;done#for w in {1..104} ; do date -d "now - $w weeks" +%Y-%m-%d ; done# Last 2 years of this weekday. Shorter easier to read version. ;-)for i in $(ls -1 /usr/share/man/man1/) ; dop=${i//.1.gz} ; echo -n "$p " ; man $p|egrep "^[\ \t]*--?[a-zA-Z0-9]"|wc -l;done# option countfor dev in `grep dev /etc/fstab | grep -v \#`; do fsck ${dev}; done# fsck my life - To do a filesystem check on all of your partitions, heres a quick one-liner. It parses out /etc/fstab for the partitions and runs a fsck on them.for dev in `grep dev /etc/fstab | grep -v \# | grep ext3 |cut -f1 -d " "`; do echo ${dev}; done# fsck my life - Or a suggested change to pull just the dev files and remove any non-ext3(insert your preferred file system format) file systems, i.e. /dev/cdrom or swap. This will not work with RHEL as Red Hat uses LABELs instead of device paths in the /etc/fstab file. Or This is what fsck does by default. Okay in actual fact it uses the values on the right to decide whether to fcsk or not (man fstab). You also probably dont want to do this on mounted filesystems (fsck -M will prevent this), and most systems already have this at startup. ALSO, fsck when given a list of devices will run in parallel against devices it feels are safely on different physical devices for extra speed.for i in *.txt; do mv $i${i%%.txt}.html; done# Change extension on a group of files using only bash builtins an -> To change the extension on a group of files using only bash builtins and mvfor i in *.txt; do mv "$i""${i%%.txt}".html; done# you forgot the quotes also see: http://www.shell-fu.org/lister.php?id=27for (( i = 0 ; i < 12; i++ )); do touch $RANDOM; done# Often it can be handy to have a few files to test another script on. A quick way to do this is to create some empty files with random names -> Just change the number (12) to give the required number of files.# orfor (( i = 0 ; i < 12; i++ )); -- long
# orfor i in $(seq 0 12); -- short
# or for i in `seq 12`; do touch $RANDOM; done# is even shorter, but not all systems have the 'seq' command - hence the original can still be useful. in the same vain as `seq 12` - for in in {1..12}; do touch $RANDOM;done ->having files named against $RANDOM seems pretty useless for testing :P in any case if you really want random use "mktemp" that is collision-safe at least.for((I=0;J=--I;))do clear;for((D=LINES;S=++J**3%COLUMNS,--D;))do printf %*s.\\n $S;done;sleep 1;done# 100 byte bash snow fieldfor((I=0;J=--I;))do clear;for((D=LINES;S=++J**3%COLUMNS,--D;))do printf %*s*\\n $S;done;sleep 0.1;done# with flakes for((I=0;J=--I;))do clear;for((D=LINES;S=++J**3%COLUMNS,--D;))do printf %*s❄\\n $S;done;sleep 0.1;done# with snowflake for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300$i thumbs/$i ; done# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPGfor i in `pip list -o --format legacy|awk '{print $1}'` ; do pip install --upgrade $i; done# Automatically update all the installed python packagesfor p in $(fuser -m /) ; do lsof -p $p ; done#for file in myDir/* ; do echo; echo "---$file--" ; cat $file ; done# cat all the files in a directory# Uppercase to lowercase with tr - The 'tr' command can be used to quickly convert uppercase to lowercase and vice versa. This is done with: tr [:upper:] [:lower:] - To give an example this can be used to rename all files in the current directory to lowercase (there are other ways to do this, but this is a decent example): Of course you can convert the other way by swapping '[:upper:]' and '[:lower:]'.for file in * ; do echo mv "$file""`echo $file | tr [:upper:] [:lower:]`"; donet=$((COLUMNS*LINES-COLUMNS));r=$((RANDOM%t));printf "\e[32m";for i in $(seq $t);do [[ $i == $r ]]&&printf "🍀"||printf "☘";done# find 4-leaft=$(($(tput cols)/3));for FR in $(seq $(tput lines));do printf "\e[44m%${t}s\e[47m%${t}s\e[41m%${t}s\e[0m\n";done# French Flag #BastilleDayo="-vvvvvv";for i in 0 {2..7}; doc="aptitude ${o:0:$i} moo";echo "$$c"; $c; done# Discover the Super Cow Powers of aptitude.for i in {1..100}; do convert -background lightblue -fill blue -size 100x100 -pointsize 24 -gravity center label:$i$i.jpg; done# Create test imagesstf=$(date +%s.%N);st=${stf/.*/};sn=%{stf/*./};for ((;;));doctf=$( date +%s.%N );ct=${ctf/.*/};cn=${ctf/*./}; echo -en "\r$(echo "scale=3; $ctf-$stf" | bc)";done# Chronometer A way for tracking times in bashstf=$(date +%s.%N);for ((;;));doctf=$( date +%s.%N );echo -en "\r$(date -u -d "0 $ctf sec - $stf sec""+%H:%M:%S.%N")";done# Chronometer in hour format Shorter and faster...NUM=-1; whileNUM=`echo $NUM + 1 | bc`; do echo $NUM && sleep 1; done# Chronometer - Chronometer using the bc calculator.stf=$(date +%s.%N);st=${stf/.*/};sn=%{stf/*./};for ((;;));doctf=$( date +%s.%N );ct=${ctf/.*/};cn=${ctf/*./}; dtf=$(echo "scale=3; $ctf-$stf" | bc); dt=${dtf/.*/}; dt=${dt:=0};echo -en "\r$(date -u -d @$dt"+%H:%M:%S.${dtf/*./}")";done# Chronometer in hour format Just add a format to chronometer in bashfor file in P*.JPG; do convert $file -resize 1280 n-$file; for file in _P*.JPG; do convert $file -resize x1280 n-$file; done# Some image bash processingfor in $i(cat list.txt); do ssh user@$i'bash command'; done# In the above example you will need to change “user” with the actual user with which you will be logging and “bash command” with the actual bash command you wish to execute. The method is better working when you are using passwordless authentication with SSH key to your machines as that way you will not need to enter the password for your user over and over again. # Note that you may need to pass some additional parameters to the SSH command depending on your Linux boxes setup.for i in G M K; do du -ah | grep [0-9]$i | sort -nr -k 1; done | head -n 11# You can use above command only if GNU/sort is installed. For other UNIX systems should use the below command.for i in 1F6{0..4}{{0..9},{A..F}} ; do printf "\\\\U$i \U$i\n" ; done# Print the Unicode emoticons block codes and symbols. for repo in repos/* ; do git -C "$repo" log | grep ^Author: ; done | sort | uniq
# Generate list of all authors in git repos under repos/for domain in $(cat dominios.txt); do nslookup -type=mx $domain ; done >ejemplo.txt
# Enumerar Registros MXfor i in log.{48..1}.gz ; do printf "$i\t" ; zgrep problem $i | wc -l ; done# Generate line stats of a problem over time in old logs. FIXEDfor i in `seq -w 1 20`; do echo $i; done# BASH For Loop - A bash script to loop 1 through 20 easily with seq.for i in *.pdf; do mv "$i" CS749__"$i"; done# Adding Prefix to File namefor i in $(aws ec2 describe-regions --output text --region "" | cut -f 3); do aws ec2 describe-images --output text --region $i --filter Name=name,Values=myimage | cut -f 6 | grep ami* | xargs -I {} aws ec2 deregister-image --region $i --image-id {};done# Cross-region delete aws ec2 imagefor i in {2018..2025}-{01..12}-13; do [[ $(date --date $i"+%u") == 5 ]] && echo "$i Friday the 13th"; done# Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy) -> Removed grep and simplified if statement. -- Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale. for i in *; doI=`echo $i|cut -c 1|tr a-z A-Z`; if [ ! -d "$I" ]; then mkdir "$I"; fi; mv "$i""$I"/"$i"; done# Sort files in folders alphabetically -> Creates one letter folders in the current directory and moves files with corresponding initial in the folder.for y in $(seq 1996 2018); do echo -n "$y -> "; for m in $(seq 1 12); doNDATE=$(date --date "$y-$m-13" +%A); if [ $NDATE == 'Friday' ]; thenPRINTME=$(date --date "$y-$m-13" +%B);echo -n "$PRINTME "; fi; done; echo; done# Calculate days on which Friday the 13th occurs -> Simply change the years listed in the first seq, and it will print out all the months in that span of years that have Friday the 13ths in them. # This is sample output - yours may be different.2010 -> August
2011 -> May
2012 -> January April July
2013 -> September December
2014 -> June
2015 -> February March November
2016 -> May
2017 -> January October
2018 -> April July
for y in $(seq 1996 2018); do echo -n "$y -> "; for m in $(seq 1 12); doNDATE=$(date --date "$y-$m-13" +%w); if [ $NDATE -eq 5 ]; thenPRINTME=$(date --date "$y-$m-13" +%B);echo -n "$PRINTME "; fi; done; echo; done# Calculate days on which Friday the 13th occurs -> I removed the dependency of the English language # This is sample output - yours may be different.1996 -> setembro dezembro
1997 -> junho
1998 -> fevereiro março novembro
1999 -> agosto
2000 -> outubro
2001 -> abril julho
2002 -> setembro dezembro
2003 -> junho
2004 -> fevereiro agosto
2005 -> maio
2006 -> janeiro outubro
2007 -> abril julho
2008 -> junho
2009 -> fevereiro março novembro
2010 -> agosto
2011 -> maio
2012 -> janeiro abril julho
2013 -> setembro dezembro
2014 -> junho
2015 -> fevereiro março novembro
2016 -> maio
2017 -> janeiro outubro
2018 -> abril julho
for i in {2018..2025}-{01..12}-13; do [[ $(date --date $i +"%u" | grep 5) != 5 ]] || echo "$i Friday the 13th"; done# Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy)Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale. Hide sample output
# This is sample output - yours may be different. 2018-04-13 Friday the 13th
2018-07-13 Friday the 13th
2019-09-13 Friday the 13th
2019-12-13 Friday the 13th
2020-03-13 Friday the 13th
2020-11-13 Friday the 13th
2021-08-13 Friday the 13th
2022-05-13 Friday the 13th
2023-01-13 Friday the 13th
2023-10-13 Friday the 13th
2024-09-13 Friday the 13th
2024-12-13 Friday the 13th
2025-06-13 Friday the 13th
for i in {2018..2022}-{01..12}-13; do date --date $i +"%Y %B %w" | sed '/[^5]$/d; s/ 5*$//'; done# Calculate days on which Friday the 13th occurs -> Alter the years in the first brace expansion to select your year range. Modify date format to your liking but leave " %w" at the end. Hide sample output# This is sample output - yours may be different.2018 April
2018 July
2019 September
2019 December
2020 March
2020 November
2021 August
2022 May
# Batch renaming in Terminal (e.g. bash) using RegEx # Example: replace every capital letter with 'abc', only changing m4a-filesfor file in *.m4a ; do mv -vf "$file""`echo $file | sed -E 's/[A-Z]/abc/g'`" ; done# Sublime-Text snippet:<snippet>
<content><![CDATA[
for file in *.${1:m4a} ; do mv -vf "\$file""`echo \$file | sed -E 's/${2:[A-Z]}/${0:abc}/g'`" ; done]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>rename</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>
#-----------------------------------------------------------------------------------------------------------------------------##Remove stored .zip archive passwords from Windows credential manager#Do not want to log out but you do want to get rid of a stored .zip file password in Windows? This will do that.for /f "tokens=2-3 delims==" %G IN ('cmdkey /list ^| find ".zip"') DO cmdkey /delete:"%G=%H"for i in $(qm list | awk '{ print $1 }' | grep -v VMID); do echo "Unlocking:"$i; qm unlock $i; echo "Unlocked"; done# loop files with SPACES on their names - use '*' instead of 'ls'for f in *;do echo $f;donefor i in {1..50} ; dod=$(( RANDOM % 29950 + 6575)) ; date -d "$d days ago" +"%F"; done# Create 50 random dates that are between 18 - 100 years ago. Used to create example birth date data.for i in $(qm list | awk '{ print $1 }' | grep -v VMID); do echo "Unlocking:"$i; qm unlock $i; echo "Unlocked"; done# Unlock VMs in Proxmox - Unlock your VMS to avoid problems after some failed tasks ended. # This is sample output ...
Unlocking: 10098Unlocked
Unlocking: 10120Unlocked
Unlocking: 11018Unlocked
Unlocking: 20003Unlocked
Unlocking: 20023...
# Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy) - Removed grep and simplified if statement. -- Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale. Show Sample Outputfor i in {2018..2025}-{01..12}-13; do [[ $(date --date $i"+%u") == 5 ]] && echo "$i Friday the 13th"; done# Day of the week of your birthday over the years.-> Do you ever want to know which day of week was your birhday! Now you can check that with this command, just set your birh date at the beginning (My bday in the example) and the dates will be revealed. ;) Show Sample Output# ...# 1999 -> Thursday# 2000 -> Saturday# 2001 -> Sunday# 2002 -> Monday# ...DAY=01; MONTH=07; YEAR=1979; CURRENT_YEAR=$(date +%Y); for i in $(seq $YEAR$CURRENT_YEAR); do echo -n "$i -> "; date --date "$i-$MONTH-$DAY" +%A; done# Count number of javascript files in subdirectories. -> I wanted to count and display the top directories containing JavaScript files in some of my project. Here it is. Maybe it can be written to more simply syntax by using find -exec...for f in `find . -type d`; do pushd . > /dev/null ; echo -e `cd $f ; find . -name \*\.js | wc -l`"\t"$f | grep -v ^0 ; popd >/dev/null; done | sort -n -k 1 -r | less
# zip-dir - zip directories - Zip all top level directoriesfor i in */; doif [ ! -f "${i%/}.zip" ]; then zip -r "${i%/}.zip""$i"; fidonefor i in 198.187.190.{0..255}; doa=$( dig +short -x $i); printf "$i: %s\n""$a"; done# Print a list of reverse DNS records for a subnet.for i in p{1..3}p{1..8}; do timeout 5m tcpdump -c 5000 -i $i -w tcpdump-${i}-20181127.pcap; done# Either log 5000 packets (-c 5000) or timeout after 5 minutes (timeout 5m) on each of 24 network tap interfaces. Did this because some interfaces may return nothing. for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300"$i""thumbs/$i" ; done# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPGfor i in {1..254};do (ping -c1 172.16.0.$i > /dev/null && echo $_) & done > pinged-hosts
# Quickly scan 172.16.0.0/24 network without using a more sophisticated tool like nmap.for p in *.jpg; do ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi; done# Make slideshow from *.jpgfor i in {1..65535};do printf "%x\n"$i;done|while read -r u;do printf "\033[38;5;$((16+$((16#$u))%230))m\u$u\033[0m";done# Unicode rainbow. Note: This may not work on Macs without changing the syntax.# Generate a sequence of numbers.for ((i=1; i<=99; ++i)); do echo $i; done# Download all .key files from your android device to your pc.for i in `adb shell "su -c find /data /system -name '*.key'"`; do mkdir -p ".`dirname $i`";adb shell "su -c cat $i" > ".$i";done# Download all default installed apk files from your android.for i in $(adb shell pm list packages | awk -F':''{print $2}'); do adb pull "$(adb shell pm path $i | awk -F':''{print $2}')"; mv *.apk $i.apk 2&> /dev/null ;done# Rename all files in lower casefor f in `find`; do mv -v "$f""`echo $f | tr '[A-Z]' '[a-z]'`"; done# Silently deletes lines containing a specific string in a bunch of files# This command will find all occurrences of one or more patterns in a collection of files and will delete every line matching the patterns in every filefor file in $(egrep 'abc|def' *.sql | cut -d":" -f1 | uniq); do sed -i '/abc/d' ./$file ; sed -i '/def/d' ./$file; done# Convert all flac files in the current directory to mp3 format using "lame"for i in *.flac; do flac -c -d "$i" | lame -m j -b 192 -s 44.1 - "${i%.flac}.mp3"; done# Make another user superuser in Ubuntufor i in $(grep :boss /etc/group | cut -f1 -d:); do adduser wife $i; done## Alternative one-liners: # ename all items in a directory to lower casefor i in *; do mv "$i""${i,,}"; done# Explanation: Loop over the items in the current directory, and use Bash built-in case modification expansion to convert to lower case.# Limitations: The case modification extension is available since Bash 4.# Unpack all of the .tar.bz2 files in current directoryfor FILE in *; do tar -jxf $FILE; done# Explanation: # for: begins the loop syntax in Bash.# FILE: can be any variable name you create.# do: this is the action you are going to tell Bash to perform on each pass of the loop.# Convert all flac files in the current directory to mp3 format using "lame"for i in *.flac; do flac -c -d "$i" | lame -m j -b 192 -s 44.1 - "${i%.flac}.mp3"; doneCalculate the average execution time (of short running scripts) with awk
for i in {1..10}; do time some_script.sh; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'# Explanation: # The for loop runs some_script.sh 10 times, measuring its execution time with time# The stderr of the for loop is redirected to stdout, this is to capture the output of time so we can grep it# grep ^real is to get only the lines starting with "real" in the output of time# sed is to delete the beginning of the line up to minutes part (in the output of time)# For each line, awk adds to the sum, so that in the end it can output the average, which is the total sum, divided by the number of input records (= NR)# Limitations: The snippet assumes that the running time of some_script.sh is less than 1 minute, otherwise it will not work at all. Depending on your system, the time builtin might work differently. Another alternative is to use the time command /usr/bin/time instead of the bash builtin.
# Check the performance of a script by re-running many times while measuring the running timefor i in {1..10}; do time curl http://localhost:8000 >/dev/null; done 2>&1 | grep real
# Explanation: # {1..10} creates a sequence from 1 to 10, for running the main script 10 times# 2>&1 redirects stderr to stdout, this is necessary to capture the "output" of the time builtin# Sort du output in Human-readable formatfor i in G M K; do du -hsx * | grep "[0-9]$i\b" | sort -nr; done 2>/dev/null
# Explanation: # The reason to use a for loop is to sort results with G or M or K values separately, otherwise sort -n would just sort everything by the numbers regardless of G M K suffix.# grep "[0-9]$i\b" matches lines containing a digit followed by G or M or K followed by a "word boundary"# Sort du output in Human-readable formatfor i in G M K; do du -hsx * | grep "[0-9]$i\b" | sort -nr; done 2>/dev/null
# Explanation: # The reason to use a for loop is to sort results with G or M or K values separately, otherwise sort -n would just sort everything by the numbers regardless of G M K suffix.# grep "[0-9]$i\b" matches lines containing a digit followed by G or M or K followed by a "word boundary"# Sort du output in Human-readable formatfor i in $(echo -e 'G\nM\nK'); do du -hsx /* 2>/dev/null | grep '[0-9]'$i | sort -rn; done# Explanation: # echo -e prints G for Gigabytes, M for Megabytes and K for Kilobytes in a line each.# 2>/dev/null send stderr to /dev/null# sort -rn sorts in reverse numerical order. Largest first# Sort du output in Human-readable formatfor i in G M K; do du -hsx * | grep "[0-9]$i\b" | sort -nr; done 2>/dev/null
# Explanation: # The reason to use a for loop is to sort results with G or M or K values separately, otherwise sort -n would just sort everything by the numbers regardless of G M K suffix.# grep "[0-9]$i\b" matches lines containing a digit followed by G or M or K followed by a "word boundary"# Sort du output in Human-readable formatfor i in $(echo -e 'G\nM\nK'); do du -hsx /* 2>/dev/null | grep '[0-9]'$i | sort -rn; done# Explanation: # echo -e prints G for Gigabytes, M for Megabytes and K for Kilobytes in a line each.# 2>/dev/null send stderr to /dev/null# sort -rn sorts in reverse numerical order. Largest first# Run command multiple times with a for loop and a sequence expressionfor i in {1..10}; do date; sleep 1; done# Explanation: This is just a regular for loop with a sequence expression. A sequence expression has the form {x..y[..incr]}, where x and y are either integers or single characters, and incr an optional increment.# More examples:# {a..f} = a b c d e f# {a..f..2} = a c e# {0..1}{0..1} = 00 01 10 11# Limitations: do not try a large range like {1..10000000000000000}, it may render your computer unusable until killed.# Log and verify files received via FTPfor i in $(cat /var/log/vsftpd.log | grep $DATE_TIME | grep UPLOAD | grep OK); do ls /FTP/HOME/$i >> /dev/null 2> \&1; if\[$? = 0\]; then echo "$i" >> $FILES_OK_UPLOADS.log; else echo "$DATE ERROR: File $i not found" >> $FTP_FILES_NOTOK_$DATE_TIME.log; fi; done# Create fattal tone mapped images from a directory of raw imagesfor img in /path/to/rawimages/*.RW2; do pfsin ${img} | pfssize -x 1024 -y 768 | pfstmo_fattal02 -v -s 1 | pfsout /path/to/finished/${img%%}.jpg; done# Explanation: for img in /path/to/rawimages/*.RW2; do Loop through image directory pfsin ${img} | read the raw image
pfssize -x 1024 -y 768 | resize it to 1024x768 because fattal looks better at low resolutions
pfstmo_fattal02 -v -s 1 | use the fattal tone mapping operator, be verbose and saturation value of 1 pfsout ./path/to/finished/${img%%}.jpg; done output and rename the file as a jpg.
# Examples of fattal tone mapped images http://goo.gl/IayQQ - pfstools website http://pfstools.sourceforge.net/# Limitations: Portrait orientation images need to be processed -x 768 -y 1024# Rename all files in a directory to upper casefor i in *; do mv "$i""${i^^}"; done# Explanation: Loop over the items in the current directory, and use Bash built-in case modification expansion to convert to upper case.# Limitations: The case modification extension is available since Bash 4.# Rename all items in a directory to lower casefor i in *; do mv "$i""${i,,}"; done# Explanation: Loop over the items in the current directory, and use Bash built-in case modification expansion to convert to lower case.# Limitations: The case modification extension is available since Bash 4.# How to expand a CIDR notation to its IPsfor j in $(seq 0 255); dofor i in $(seq 0 255) ; do seq -f "10.$j.$i.%g"0 255; done; done# Explanation: Using two for loops to create second & third block of IP and finally through a formatted seq to printf the output. More efficient/using less memory than using {..} (range).# Limitations: seq is not available by default in some systems.# Find which log files contain or do not contain a specific error messagefor i in *.log; do grep OutOfMemo $i >/dev/null && echo $i oom || echo $i ok; done# Explanation: In this example I was looking for a list of log files which contain or do not contain a stack trace of OutOfMemoryError events.# for i in *.log is to loop over the list of files.# For each file, I run grep, but redirect the output to /dev/null, as I do not need that, I just want to see a "yes or no" kind of summary for each file# grep exits with success if it found any matching lines, otherwise with failure. Using the pattern cmd && success || failure, I echo the filename and the text "oom" in case of a match, or "ok" otherwise# Remarks:# Using grep -q is equivalent to redirecting output to /dev/null, but might not be supported in all systems# grep -l can be used to list files with matches, and grep -L to list files without matches, but the latter does not exist in some implementations of grep, such as BSD# I realized it a bit late, but grep -c shows a count of the matches, so actually it could have been a suitable and simpler solution# Limitations: could be put in a loop like thisfor A in $(printf %08X'\n'256 255); do echo $A | grep -o .. | tac | tr -d '\n'; done# Convert directory of videos to MP4 in parallelfor INPUT in *.avi ; do echo "${INPUT%.avi}" ; done | xargs -i -P9 HandBrakeCLI -i "{}".avi -o "{}".mp4
# Explanation: This oneliner uses the wonderful Handbrake program to convert videos. We convert a directory of AVIs at a time, in parallel. The first three bits ("for INPUT...done |") lists the AVI files in the current directory, then uses a Bash function to strip off the suffix. It then sends each video file name to the next part.# The next part of the command (| xargs ...) runs our converter in parallel. The "-i" flag says take each input (video file name) and stick it in the "{}" parts of the xargs command. The parallel option lets us run up to 9 commands at the same time ("-P9").# The last part (HandBrakeCLI -i "{}".avi -o "{}".mp4) converts a single video to MP4 format. The two open-close curly braces are replaced with xargs, once per input video file. The first run through will be "HandBrakeCLI -i "input1".avi -o "input1".mp4", next will be "HandBrakeCLI -i "input2".avi -o "input2".mp4", etc.# Convert all flac files in dir to mp3 320kbps using ffmpegfor FILE in *.flac; do ffmpeg -i "$FILE" -b:a 320k "${FILE[@]/%flac/mp3}"; done;
# Explanation: It loops through all files in current directory that have flac extension and converts them to mp3 files with bitrate of 320kpbs using ffmpeg and default codec.# Generate a sequence of numbersfor ((i=1; i<=10; ++i)); do echo $i; done# Explanation: This is similar to seq, but portable. seq does not exist in all systems and is not recommended today anymore. Other variations to emulate various uses with seq:# seq 1 2 10for ((i=1; i<=10; i+=2)); do echo $i; done# seq -w 5 10for ((i=5; i<=10; ++i)); do printf '%02d\n'$i; done# Delete static and dynamic arp for /24 subnetfor i in {1..254}; do arp -d 192.168.0.$i; done# Explanation: Simply loop from 1 to 254 and run arp -d for each IP address in the 192.168.0.0/24 network.# Create a txt files with 10000 rowsfor FILE in *.full ; do split -l 100000$FILE; mv -f xaa `echo "$FILE" | cut -d'.' -f1`.txt; rm -f x*; done# Explanation: for loop will go trough every file that is finished with ".full" split that in file in files of 100000 rows. Rename the first one as input name but deleting the extension and adding ".txt" as extension. As last stem it will delete the rest of split files.# Up all docker services as detached mode over all immediate subdirectoriesfor dir in $(ls -d */); do eval $(cd $PWD/$dir && docker-compose up -d && cd ..); done;
# Explanation: Supposing that you are in a directory that contains many subdirectories with a docker-compose file each one and instead of up one by one manually you want run all at time, well this is a helpful command for this purpose# Take values from a list (file) and search them on another filefor ITEM in `cat values_to_search.txt`; do (egrep $ITEM full_values_list.txt && echo $ITEM found) | grep "found" >> exit_FOUND.txt; done# Explanation: This line :) searches values taken from a file (values_to_search.txt) by scanning a full file values list . If value found, it is added on a new file exit_FOUND.txt. Alternatively, we can search for values from the list 1 which does NOT exists on the list 2, as bellow:for ITEM in cat values_to_search.txt; do (egrep $ITEM full_values_list.txt || echo $ITEM not found) | grep "not found">> exit_not_found.txt; done# Limitations: No # Limitations: -
for i in {1..12} $(grep ^ru <<<$LANG);do printf "\e[32m%10s{\e[31m@\n\e[0m"|tr " " =; done# Is your sweetheart a shell user? Give them an ASCII/ANSI bouquet. Provide an extra one for Russian speakers because they prefer odd quantities of flowers. Add to their shell rc file. Mehr jessie frazelle hat cron mom retweetet I have to google the way the fucking arrows and numbers go for “2>&1” every damn time, ie “redirect stderrr to stdout”jessie frazelle hat hinzugefügt, cron momfor a in *.pdf ; do pdfcrop --margins '0 -575 0 -10'$a`basename $a .pdf`-notes.pdf ; done# pdfcrop came to my rescue to extract a section at the bottom of each page on a large number of pdf files: https://github.com/mvp/uhubctl # Linux users with an compatible USB hub can use uhubctl to turn on/off that USB fan, light, vacuum cleaner.for f in *.zip; do unzip -d "${f%*.zip}""$f"; done# Make a dedicated folder for each zip file {f%*.zip} strips off the extension from zip filenames# Create a txt files with 10000 rowsfor FILE in *.full ; do split -l 100000$FILE; mv -f xaa `echo "$FILE" | cut -d'.' -f1`.txt; rm -f x*; done# Up all docker services as detached mode over all immediate subdirectoriesfor dir in $(ls -d */); do eval $(cd $PWD/$dir && docker-compose up -d && cd ..); done;
# I wrote a countdown alarm with graphic output for cooking with one line of code, the power of command line: clear; for i in `seq 60 -1 1`; do banner $i; sleep 1; clear; done ; play -n synth .8 sine 4100 fade q 0.1 .3 0.1 repeat 3# Interactively delete broken links in folderfor f in $( file . | grep broken | cut -d':' -f 1); do rm -i $f; done# Prepend to filenamefor file in ; do mv $file'Pandoras_Box_'$file ; done# Undo above (delimiter arg may need to be tweaked here)for file in ; do mv $file`echo $file | cut -f3 -d_` ; done# Replace all spaces with underscores in file name# For recursive see http://stackoverflow.com/questions/2709458/bash-script-to-replace-spaces-in-file-namesfor f in \ ; do mv "$f""${f// /_}"; done# files for ls to digest... in which case the same command would work with echo instead: for i in $(echo [0-9]*.png); do mv $i$(echo $i | awk -F".png"'{ printf "%05d\n",$1}').png;done# Good for upto almost 10k numbered filenamesfor i in $(ls [0-9]*.png); do mv $i$(echo $i | awk -F".png"'{ printf "%05d\n",$1}').png;done# Sometimes you want to generate a list of valid dates for the year. Use {0..365} on a leap year. This uses GNU date syntax.for d in {0..364} ; do date -d "2019-01-01 + $d days" +%Y%m%d ; done# Fix some files (matching 3.png, 4.png, ... 9.png) so that they have leading zeros for proper ordering.for i in [3-9].png ; do mv $i 0$i ; done#shell bash iterate number range with for loop# "seq" has an additional parameter to use as INCREMENT. # seq FIRST INCREMENT LAST https://linux.die.net/man/1/seq for i in $(seq 1 5) ; do echo $i ; done#This is sample output - yours may be different.12345#Block all IPv4 addresses that has brute forcing our ssh server#For ipv6 use: grep -oE "\b([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\b"for idiots in "$(cat /var/log/auth.log|grep invalid| grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b')"; do iptables -A INPUT -s "$idiots" -j DROP; done#shell bash iterate number range with for loop#Bashs arithmetic evaluation.for((i=1;i<=10;i++)){ echo $i; }
#shell bash iterate number range with for loopfor i in {1..10}; do echo $i; done#shell bash iterate number range with for looprangeBegin=10; rangeEnd=20; for ((numbers=rangeBegin; numbers<=rangeEnd; numbers++)); do echo $numbers; done#shell bash iterate number range with for loop#iterating range of numer with for loop in shell or bash rangeBegin=10; rangeEnd=20; for numbers in $(eval echo "{$rangeBegin..$rangeEnd}"); do echo $numbers;done# This is sample output - yours may be different.1011121314151617181920# convert raw camera image to jpeg - raw image created by canon digital camera. Install using apt-get install ufrawfor i in *.CR2; do ufraw-batch $i --out-type=jpeg --output $i.jpg; done;
# Scan all open ports without any required programfor i in {1..65535}; do (echo < /dev/tcp/127.0.0.1/$i) &>/dev/null && printf "\n[+] Open Port at\n: \t%d\n""$i" || printf "."; done# Massive change of file extension (bash) - Change the file extension in batch. Useful to create output file names with same input name but distinct extension by including logic inside the loopfor file in *.txt; do mv "$file""${file%.txt}.xml"; done# Generate a sequence of numbersfor i in {1..10};do echo $i;done# Rename all files in a directory to the md5 hashfor i in *; dosum=$(md5sum $i); mv -- "$i""${sum%% *}"; done# shell bash iterate number range with for loop -> Bash's arithmetic evaluation.for((i=1;i<=10;i++)){ echo $i; }
# shell bash iterate number range with for loopfor i in {1..10}; do echo $i; done# shell bash iterate number range with for loop -> "seq" has an additional parameter to use as INCREMENT. # seq FIRST INCREMENT LAST https://linux.die.net/man/1/seqfor i in $(seq 1 5) ; do echo $i ; done# Sample output# 1# 2# 3# 4# 5# get all Google ipv4/6 subnets for a iptables firewall for example (updated version) - google has added 2 more netblocks...for NETBLOCK in $(echo _netblocks.google.com _netblocks2.google.com _netblocks3.google.com); do nslookup -q=TXT $NETBLOCK ; done | tr " ""\n" | grep ^ip[46]: | cut -d: -f2- | sort
# Sample output# 108.177.8.0/21# 108.177.96.0/19# 209.85.128.0/17# 216.239.32.0/19# 216.58.192.0/19# 2404:6800:4000::/36# 2c0f:fb50:4000::/36# 35.190.247.0/24# 66.249.80.0/20# 72.14.192.0/18# 74.125.0.0/16# Find a file and then copy to tmp folder - Select only the files with given name and copy them to /tmp/ folder.for file in `ls | grep -i 'mumbai|pune|delhi'` ; do cp $file /tmp/ ; done# Massive change of file extension (bash) - Using bash parameters expansionfor file in *.txt; do mv "${file%.txt}{.txt,.xml}"; done#==============================##==============================## CMD for ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command for in a clear format. This allows users to quickly access the needed information for for without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for for are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the keytool command with important options and switches using examples.
# ██╗ ██╗███████╗██╗ ██╗████████╗ ██████╗ ██████╗ ██╗ # ██║ ██╔╝██╔════╝╚██╗ ██╔╝╚══██╔══╝██╔═══██╗██╔═══██╗██║ # █████╔╝ █████╗ ╚████╔╝ ██║ ██║ ██║██║ ██║██║ # ██╔═██╗ ██╔══╝ ╚██╔╝ ██║ ██║ ██║██║ ██║██║ # ██║ ██╗███████╗ ██║ ██║ ╚██████╔╝╚██████╔╝███████╗# ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝keytool -list -providerpath bcprov-jdk15on-1.60.jar -provider org.bouncycastle.jce.provider.BouncyCastleProvider -storetype BCPKCS12 -storepass <passphrase> -keystore <filename>
# keytool view all entries in a keystore with BouncyCastle as security provider This command lists the fingerprints of all of the certificates in the keystore, using BouncyCastle as security provider. Show Sample Output:# $> keytool -list \# -providerpath bcprov-jdk15on-1.60.jar \# -provider org.bouncycastle.jce.provider.BouncyCastleProvider \# -storetype BCPKCS12 \# -storepass <passphrase> \# -keystore keystore <enter># Keystore type: BCPKCS12# Keystore provider: BC# Your keystore contains 2 entries# encipher, Feb 20, 2019, trustedCertEntry,# Certificate fingerprint (SHA1): XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX# signer, Feb 20, 2019, trustedCertEntry,# Certificate fingerprint (SHA1): XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XXkeytool -importkeystore -providerpath bcprov.jar -provider BouncyCastleProvider -srckeystore <filename.pfx> -srcstoretype pkcs12 -srcalias <src-alias> -destkeystore <filename.ks> -deststoretype BCPKCS12 -destails <dest-alias>
# keytool using BouncyCastle as security provider to add a PKCS12 certificate store This command imports the keystore file cert.pfx into the keystore file, using BouncyCastle as security provider. It was validated using - OpenJDK Runtime Environment (Zulu 8.36.0.1-CA-linux64) - Java(TM) SE Runtime Environment (build 1.8.0_192-ea-b04) - OpenJDK Runtime Environment (build 9.0.4+11) - OpenJDK Runtime Environment 18.9 (build 11.0.2+9) Show Sample Output:# keytool -importkeystore \# -providerpath bcprov-jdk15on-1.60.jar \# -provider org.bouncycastle.jce.provider.BouncyCastleProvider \# -srckeystore cert.pfx \# -srcstoretype pkcs12 \# -srcalias 1 \# -destkeystore keystore \# -deststoretype BCPKCS12 \# -destalias 'mycert'# Importing keystore cert.pfx to keystore...keytool -importcert -providerpath bcprov-jdk15on-1.60.jar -provider org.bouncycastle.jce.provider.BouncyCastleProvider -storetype BCPKCS12 -trustcacerts -alias <alias> -file <filename.cer> -keystore <filename>
# keytool using BouncyCastle as security provider to add a X509 certificate This command imports the certificate file cert.pfx into the keystore file, using BouncyCastle as security provider. It was validated using - OpenJDK Runtime Environment (Zulu 8.36.0.1-CA-linux64) - Java(TM) SE Runtime Environment (build 1.8.0_192-ea-b04) - OpenJDK Runtime Environment (build 9.0.4+11) - OpenJDK Runtime Environment 18.9 (build 11.0.2+9) Show Sample Output:
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command keytool in a clear format. This allows users to quickly access the needed information for keytool without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for keytool are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the markdown command with important options and switches using examples.
# ███╗ ███╗ █████╗ ██████╗ ██╗ ██╗██████╗ ██████╗ ██╗ ██╗███╗ ██╗# ████╗ ████║██╔══██╗██╔══██╗██║ ██╔╝██╔══██╗██╔═══██╗██║ ██║████╗ ██║# ██╔████╔██║███████║██████╔╝█████╔╝ ██║ ██║██║ ██║██║ █╗ ██║██╔██╗ ██║# ██║╚██╔╝██║██╔══██║██╔══██╗██╔═██╗ ██║ ██║██║ ██║██║███╗██║██║╚██╗██║# ██║ ╚═╝ ██║██║ ██║██║ ██║██║ ██╗██████╔╝╚██████╔╝╚███╔███╔╝██║ ╚████║# ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝# headersh1 header=========
h2 header
---------
# blockquotes> first level and paragraph
>> second level and first paragraph
>
> first level and second paragraph
# lists## unordered - use *, +, or - * Red
* Green
* Blue
## ordered 1. First
2. Second
3. Third
# code - use 4 spaces/1 tabregular text
code code code
or:
Use the `printf()`function# hr's - three or more of the following***
---
___
# linksThis is [an example](http://example.com "Title") inline link.
# image
# emphasis*em* _em_
**strong** __strong__
#==============================##==============================## CMD MARKDOWN ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command markdown in a clear format. This allows users to quickly access the needed information for markdown without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for markdown are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the ocaml command with important options and switches using examples.
# ██████╗ ██████╗ █████╗ ███╗ ███╗██╗ # ██╔═══██╗██╔════╝██╔══██╗████╗ ████║██║ # ██║ ██║██║ ███████║██╔████╔██║██║ # ██║ ██║██║ ██╔══██║██║╚██╔╝██║██║ # ╚██████╔╝╚██████╗██║ ██║██║ ╚═╝ ██║███████╗# ╚═════╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝# OCaml# OCaml, originally named Objective Caml, is the main implementation of the programming language Caml.# A member of the ML language family.# Compile into a bytecode executable:ocamlc hello.ml -o hello
# Compile into an optimized native-code executable:ocamlopt hello.ml -o hello
# Start ocaml interactive shellocaml
# Start the shiny frontend to the ocaml interactive shell, utop# to install it: opam install utoputop
# See also:# OCaml language cheat sheets at /ocaml/# list of pages: /ocaml/:list# learn perl: /ocaml/:learn# ocaml one-liners: /ocaml/1line# search in pages: /ocaml/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command ocaml in a clear format. This allows users to quickly access the needed information for ocaml without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for ocaml are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the opam command with important options and switches using examples.
# ██████╗ ██████╗ █████╗ ███╗ ███╗# ██╔═══██╗██╔══██╗██╔══██╗████╗ ████║# ██║ ██║██████╔╝███████║██╔████╔██║# ██║ ██║██╔═══╝ ██╔══██║██║╚██╔╝██║# ╚██████╔╝██║ ██║ ██║██║ ╚═╝ ██║# ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝# OPAM is a source-based package manager for OCaml# Initialize ~/.opam using an already installed OCamlopam init
opam init --comp 4.02.3
# Initialize with a freshly compiled OCaml 4.02.3# List all available packagesopam list -a
# List packages with QUERY in their name or descriptionopam search ${QUERY}# Display information about PACKAGEopam show ${PACKAGE}# Download, build and install the latest version of PACKAGE# and all its dependenciesopam install ${PACKAGE}# Update the packages databaseopam update
# Bring everything to the latest version possibleopam upgrade
# Command-specific manpageopam CMD --help
# install static analysis and indentation for ocamlopam install ocp-indent merlin
# configure editor as recommended in the installation output# + (for vim) don't forget to add "filetype plugin on" in ~/.vimrc
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command opam in a clear format. This allows users to quickly access the needed information for opam without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for opam are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the php command with important options and switches using examples.
# ██████╗ ██╗ ██╗██████╗ # ██╔══██╗██║ ██║██╔══██╗# ██████╔╝███████║██████╔╝# ██╔═══╝ ██╔══██║██╔═══╝ # ██║ ██║ ██║██║ # ╚═╝ ╚═╝ ╚═╝╚═╝ # PHP is a server-side scripting language designed primarily for web development # but also used as a general-purpose programming language # To view the php version:php -v
# To view the installed php modules:php -m
# To view phpinfo() information:php -i
# To lint a php file:php -l file.php
# To lint all php files within the cwd:find . -name "*.php" -print0 | xargs -0 -n1 -P8 php -l
# To enter an interactive shell:php -a
# To locate the system's php.ini files:php -i | grep "php.ini"# To start a local webserver for the cwd on port 3000 (requires php >= 5.4):php -S localhost:3000
# See also:# PHP language cheat sheets at /php/# list of pages: /php/:list# search in pages: /php/~keyword#==============================##==============================## CMD PHP ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command php in a clear format. This allows users to quickly access the needed information for php without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for php are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the pip command with important options and switches using examples.
# ██████╗ ██╗██████╗ # ██╔══██╗██║██╔══██╗# ██████╔╝██║██████╔╝# ██╔═══╝ ██║██╔═══╝ # ██║ ██║██║ # ╚═╝ ╚═╝╚═╝ # Search for packagespip search SomePackage
# Install some packagespip install SomePackage
# Install some package in user spacepip install --user SomePackage
# Upgrade some packagepip install --upgrade SomePackage
# Output and install packages in a requirement filepip freeze > requirements.txt
pip install -r requirements.txt
# Show details of a packagepip show SomePackage
# List outdated packagespip list --outdated
# Upgrade all outdated packages, thanks to http://stackoverflow.com/a/3452888pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
# Install specific version of a packagepip install -I SomePackage1==1.1.0 'SomePackage2>=1.0.4'# Convert pip list --outdated for reuse in pip install -Upip install -U $(pip list --outdated 2> /dev/null | grep -v 'Version' | grep -v '------' | awk '{printf $1 " " }' && echo)# Convert pip list --outdated for reuse in pip install -Upython3 -m pip install -U $(python3 -m pip list outdated 2> /dev/null | grep -v 'Version' | grep -v '\-\-\-\-\-\-' | awk '{printf $1 " " }' && echo)#==============================##==============================## CMD PIP ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command pip in a clear format. This allows users to quickly access the needed information for pip without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for pip are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the pip3 command with important options and switches using examples.
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command pip3 in a clear format. This allows users to quickly access the needed information for pip3 without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for pip3 are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the python3-behave command with important options and switches using examples.
# ██████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ ███╗ ██╗██████╗ ██████╗ ███████╗██╗ ██╗ █████╗ ██╗ ██╗███████╗# ██╔══██╗╚██╗ ██╔╝╚══██╔══╝██║ ██║██╔═══██╗████╗ ██║╚════██╗ ██╔══██╗██╔════╝██║ ██║██╔══██╗██║ ██║██╔════╝# ██████╔╝ ╚████╔╝ ██║ ███████║██║ ██║██╔██╗ ██║ █████╔╝█████╗██████╔╝█████╗ ███████║███████║██║ ██║█████╗ # ██╔═══╝ ╚██╔╝ ██║ ██╔══██║██║ ██║██║╚██╗██║ ╚═══██╗╚════╝██╔══██╗██╔══╝ ██╔══██║██╔══██║╚██╗ ██╔╝██╔══╝ # ██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║██████╔╝ ██████╔╝███████╗██║ ██║██║ ██║ ╚████╔╝ ███████╗# ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝# Get number of all Python Behave scenarios (including all examples from Scenario Outlines)behave -d | grep "scenarios passed" | cut -d, -f4 | sed -e 's/^[[:space:]]*//' | sed 's/untested/scenarios/g'# Explanation: behave -d# -d stands for dry-run, so behave invokes formatters without executing the steps.# grep "scenarios passed"# Then we grep for the summary line containing number of all scenarios# cut -d, -f4# then we cut the last value from selected summary line that show how many scenarios were "untested" (in this context it means not executed, which is exactly what we need)# sed -e 's/^[[:space:]]*//'# Trim leading space# sed 's/untested/scenarios/g'# Lastly simple sed to replace untested with scenarios
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command python3-behave in a clear format. This allows users to quickly access the needed information for python3-behave without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for python3-behave are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the rustup command with important options and switches using examples.
# ██████╗ ██╗ ██╗███████╗████████╗██╗ ██╗██████╗ # ██╔══██╗██║ ██║██╔════╝╚══██╔══╝██║ ██║██╔══██╗# ██████╔╝██║ ██║███████╗ ██║ ██║ ██║██████╔╝# ██╔══██╗██║ ██║╚════██║ ██║ ██║ ██║██╔═══╝ # ██║ ██║╚██████╔╝███████║ ██║ ╚██████╔╝██║ # ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═════╝ ╚═╝# rustup# The Rust toolchain installer # update rustup toolchainrustup update
# install nightly buildrustup install nightly
# use rustc from nightly toolchainrustup run nightly rustc --version
# switch to nightly installationrustup default nightly
# List all available targets for the active toolchainrustup target list
# Install the Android targetrustup target add arm-linux-androideabi
# Run a shell configured for the nightly compilerrustup run nightly bash
# Show which toolchain will be used in the current directoryrustup show
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command rustup in a clear format. This allows users to quickly access the needed information for rustup without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for rustup are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the shellcheck command with important options and switches using examples.
# ███████╗██╗ ██╗███████╗██╗ ██╗ ██████╗██╗ ██╗███████╗ ██████╗██╗ ██╗# ██╔════╝██║ ██║██╔════╝██║ ██║ ██╔════╝██║ ██║██╔════╝██╔════╝██║ ██╔╝# ███████╗███████║█████╗ ██║ ██║ ██║ ███████║█████╗ ██║ █████╔╝ # ╚════██║██╔══██║██╔══╝ ██║ ██║ ██║ ██╔══██║██╔══╝ ██║ ██╔═██╗ # ███████║██║ ██║███████╗███████╗███████╗╚██████╗██║ ██║███████╗╚██████╗██║ ██╗# ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝ ╚═╝# shellcheck# Shell script static analysis tool.# Check a shell script:shellcheck file.sh
# Override script's shebang:shellcheck --shell sh|bash|ksh file.sh
# Ignore certain errors:shellcheck --exclude SC1009 file.sh
# Ignore multiple errors:shellcheck --exclude SC1009,SC1073 file.sh
# To disable some check, e.g. SC2034, for a statement in code add comment with the following lineshellcheck disable=SC2034
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command shellcheck in a clear format. This allows users to quickly access the needed information for shellcheck without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for shellcheck are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the solidity command with important options and switches using examples.
# ███████╗ ██████╗ ██╗ ██╗████████╗██╗████████╗██╗ ██╗# ██╔════╝██╔═══██╗██║ ██║╚══██╔══╝██║╚══██╔══╝╚██╗ ██╔╝# ███████╗██║ ██║██║ ██║ ██║ ██║ ██║ ╚████╔╝ # ╚════██║██║ ██║██║ ██║ ██║ ██║ ██║ ╚██╔╝ # ███████║╚██████╔╝███████╗██║ ██║ ██║ ██║ ██║ # ╚══════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ # Solidity is a contract-oriented, high-level language for implementing smart contracts.# It is designed to target the Ethereum Virtual Machine (EVM).# To create a contract, declare which solidity version the source code is written forpragma solidity ^0.4.0;
# See also:# Solidity language cheat sheets at /solidity/# list of pages: /solidity/:list# learn solidity: /solidity/:learn# search in pages: /solidity/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command solidity in a clear format. This allows users to quickly access the needed information for solidity without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for solidity are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the virtualenv command with important options and switches using examples.
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command virtualenv in a clear format. This allows users to quickly access the needed information for virtualenv without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for virtualenv are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the while command with important options and switches using examples.
# ██╗ ██╗██╗ ██╗██╗██╗ ███████╗# ██║ ██║██║ ██║██║██║ ██╔════╝# ██║ █╗ ██║███████║██║██║ █████╗ # ██║███╗██║██╔══██║██║██║ ██╔══╝ # ╚███╔███╔╝██║ ██║██║███████╗███████╗# ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝╚══════╝╚══════╝while sleep 30; do curl -s 192.168.0.106 |jq '.temp'|awk '$1>80'|ts ;done# Print temperature value from sensor w/ time when temp is over 80while sleep 30; do curl -s 192.168.0.106 |egrep "temp: 8[0-9]" | ts ;done# Output json data from sensor w/ time when temp reaches over 80.while sleep 1;do tput sc;tput cup 0$(($(tput cols)-29));date;tput rc;done &
# Just execute the below command on you prompt and see the date and time on the above right corner of terminal.while :;do rec -t raw /dev/null rate 32k silence 1 0.1 2% 1 0.0 2% && ping -c 1 home;sleep 1; done# Ping home when mic "hears" something.while read -s; do date +%H:%M; done |uniq -c
# Press enter every time you hear child cough to determine if per min rate is going down.while read line; do echo "line length is ${#line}"; done# While loops are good for reading data from stdin and running processes against itwhile :; do echo beeww beeeeooooowwwww dun dun dun dun brtbrtbrt | espeak --stdout | play - pitch -400 bend .3,-600,.3 ; done#while ! curl -m 10 http://www.example\.com/ ; do echo still down ; sleep 1m ; done ; play alarm.wav
# Play alarm.wav once site is back.while :; do echo wub wub wub | espeak --stdout | play - pitch -400 bend .3,-600,.3 ; done# CLI generated dubstep. while :;do curl -Ls "X\.com"|md5sum;sleep 5m;done|awk '{if(NR>1&&l!=$1){system("echo the site changed|mail -s NOTIFY you@isp\.net");};l=$1}'while true; dofor i in 02E{{9..5},{6..8}}; do printf "\u${i}O=o>";sleep 0.09;printf "\b\b\b\b\b";done;printf "_";done# Pave the road.while true;doN=$(($RANDOM % $COLUMNS));for i in $( seq 1$N);do echo -n " ";done;echo \*;done# Snow storm in the terminalwhile :;do wget http://example\.com/exposed -O exposed-$(date +%Y%m%d%H%M%S)||break;sleep 1h;done# Get data and timestamp til 40X statuswhile true;dofor i in ~/Pictures/*.jpg ;do cp "$i" ~/slideshow.jpg ;sleep 5;done; done# Poor mans auto updating slideshow image.while :;do iwlist wlan0 scan |awk -F\"'/ESSID/{print $2}' |espeak;done# Your Linux laptop says ESSID names while you drive around.while sleep 30; do curl -s 192.168.0.106 |jq '.temp'|awk '$1>80'|ts ;done# Print temperature value from sensor w/ time when temp is over 80while sleep 30; do curl -s 192.168.0.106 |egrep "temp: 8[0-9]" | ts ;done# Output json data from sensor w/ time when temp reaches over 80.while :;do rec -t raw /dev/null rate 32k silence 1 0.1 2% 1 0.0 2% && ping -c 1 home;sleep 1; done# Ping home when mic "hears" something.while read -s; do date +%H:%M; done |uniq -c
# Press enter every time you hear child cough to determine if per min rate is going down.while read line; do echo "line length is ${#line}"; done# While loops are good for reading data from stdin and running processes against itwhile true; dofor i in 02E{{9..5},{6..8}}; do printf "\u${i}O=o>";sleep 0.09;printf "\b\b\b\b\b";done;printf "_";done# Pave the road.while :;do wget http://example\.com/exposed -O exposed-$(date +%Y%m%d%H%M%S)||break;sleep 1h;done# Get data and timestamp til 40X statuswhile :; do echo beeww beeeeooooowwwww dun dun dun dun brtbrtbrt | espeak --stdout | play - pitch -400 bend .3,-600,.3 ; done#while ! curl -m 10 http://www.example\.com/ ; do echo still down ; sleep 1m ; done ; play alarm.wav
# Play alarm.wav once site is back.while :; do echo wub wub wub | espeak --stdout | play - pitch -400 bend .3,-600,.3 ; done# CLI generated dubstep. while true;dofor i in ~/Pictures/*.jpg ;do cp "$i" ~/slideshow.jpg ;sleep 5;done; done# Poor mans auto updating slideshow image.while :;do curl -Ls "X\.com"|md5sum;sleep 5m;done|awk '{if(NR>1&&l!=$1){system("echo the site changed|mail -s NOTIFY you@isp\.net");};l=$1}'i=10; while [ $i -gt 0 ]; do echo $i seconds remaining; i=`expr $i - 1`; sleep 1; done# cli countdown 10 -> 0while :;do iwlist wlan0 scan |awk -F\"'/ESSID/{print $2}' |espeak;done# Your Linux laptop says ESSID names while you drive around.while true;do iwlist wlan0 scan |awk -F\"'/ESSID/{print $2}' |espeak;done# Your laptop says ESSID names while you drive around.while true; do echo "Hey look shells." ; sleep 1 ; done#while sleep 5; do pgrep wget > /dev/null || { date ; systemctl suspend ; break ; }; done# Suspend computer after wget exitw=50;whilev=$((${RANDOM:0:1}-3)); do read -p "Balance: $w | Play? (y/N) " a; [[ "$a" == "y" ]] && w=$((w+v));[[ $w -lt 0 ]] && break; done#while [ 1 ];dovardate=$(date +%d\-%m\-%Y\_%H.%M.%S);COUNTER=$((COUNTER + 1)); screencapture -t jpg -x ~/stockmon/$COUNTER.jpg; sleep 5; done;
# BASH Timelapsed Screenshot scriptwhile true; do echo "$(date '+%D %T' | toilet -f term -F border --gay)"; sleep 1; done#while :; do xinput --query-state 10 |grep -q 'button\[1\]=down' && [[ $((RANDOM%20)) == 1 ]] && mplayer ScoobyHewoo.wav; sleep 0.2 ; done# Rnd Playlistwhile :; do [ ! -z "$a" ] && { a=""; xsel <<<"$a"; } || a=$(xsel); sleep 10; done# Clear your copy buffer after 10-20 seconds. #infosecn=1;while :;do xinput --query-state 8|grep 'button\[1\]=d' &&{ xdotool type "$n"; n=$[n+1]; };sleep 0.3;done# Auto type next $n on click# Poly synth. Press asdfghj. Uses sox.n=CDEFGAB;l=asdfghj;while read -n1 k;dox=$(tr $l$n<<<$k);play -qn synth pl ${x}3 fade 0 .7 & done# Watch the Unix clock in style as it approaches 1.5 billion seconds. >10 hours to go.while date +%s | figlet ; do sleep 1 ; clear ; done# "Infinite" data breachwhile :;do rig |head -1 |tr '\n' ,;echo $RANDOM{,,,,} |tr -d ' ' ;done |sed -r -e 's/,(...)(..)(....).*/,\1-\2-\3/'while :; do diskutil apfs list | grep Decryption | awk {'print $4'}; sleep 10; done# Monitor FileVault progress during encryption/decryption# hardcode dnsserver, no more rewriting of etc/resolv.conf -> runs in background rewriting /etc/resolv.conf periodically dnswhile sudo sed -i -e 's/^\(nameserver\).*$/\1 $dns/' /etc/resolv.conf; do sleep 15; done &
# simple pomodorowhile true; do sleep $((40 * 60)); echo "Fuck away for some time"; sleep $((3 * 60)); done &
while true; do sleep .15; head /dev/urandom | tr -dc A-Za-z0-9; done# Continuous random string of text# Don't watch the clock yourself, run date after the last dd command is done.while pidof dd ; do sleep 1; done; date
# Watch the Unix clock in style with figlet and lolcat. Tonight it passes over 1555555555 seconds.while date +%s | figlet | lolcat ; do sleep 1 ; clear ; done# While loop to pretty print system load (1, 5 & 15 minutes)while [ 1 == 1 ]; do cat /proc/loadavg | awk '{printf "1 minute load: %.2f\n", $(NF-5)}' && cat /proc/loadavg |awk '{printf "5 minute load: %.2f\n", $(NF-3)}' && cat /proc/loadavg |awk '{printf "15 minute load: %.2f\n", $(NF-2)}'; sleep 3; date; done# While loop to pretty print system load (1, 5 & 15 minutes)while :; do date; awk '{printf "1 minute load: %.2f\n", $1; printf "5 minute load: %.2f\n", $2; printf "15 minute load: %.2f\n", $3}' /proc/loadavg; sleep 3; donewhile(1 -eq 1 ) {Get-Process -Name *APPNAME* | Select-Object -ExpandProperty ID | ForEach-Object {Get-NetTCPConnection -OwningProcess $_} -ErrorAction SilentlyContinue }
# Application network trace based on application name# This command takes an application name as an argument and then it will listen to the tcp traffic and capture packets matching the process Id of the application. The output shows: local address / local port / Remote Address / Remote port / State / Owning Process ID This is sample output - yours may be different.# 192.168.0.1 50306 8.8.8.8 443 Established Internet 21128# While loop to pretty print system load (1, 5 & 15 minutes)while :; do date; awk '{printf "1 minute load: %.2f\n", $1; printf "5 minute load: %.2f\n", $2; printf "15 minute load: %.2f\n", $3}' /proc/loadavg; sleep 3; done# Explanation: while :; do ...; done is an infinite loop. You can interrupt it with Control-c. The file /proc/loadavg contains a line like this: 0.01 0.04 0.07 1/917 25383# Where the first 3 columns represent the 1, 5, 15 minute loads, respectively. In the infinite loop we print the current date, then the load values nicely formatted (ignore the other values), then sleep for 3 seconds, and start again.# Limitations: /proc/loadavg is only available in Linux.## Related one-liners# While loop to pretty print system load (1, 5 & 15 minutes)while [ 1 == 1 ]; do cat /proc/loadavg | awk '{printf "1 minute load: %.2f\n", $(NF-5)}' && cat /proc/loadavg |awk '{printf "5 minute load: %.2f\n", $(NF-3)}' && cat /proc/loadavg |awk '{printf "15 minute load: %.2f\n", $(NF-2)}'; sleep 3; date; done# Explanation: top is great but this will make it easier to read and makes it easy to pipe to text file for historical review. kill with ctrl+c# Passwords and username guessing or checks:while read line; dousername=$line; while read line; do smbclient -L yTARGET IP ADDRESS> -U $username%$line -g -d 0; echo $username:$line; done<<PASSWORDS>.txt; done<<USERNAMES>.txt
while [ true ]; do cat /proc/loadavg | perl -ne 'm/(^[^ ]+)/; $L = $1; $s=0.5 + $L; print "*" x $s; print " $L\n";' ; sleep 6; done
# It takes the first value of /prov/loadavg to print that many stars followed by the value. to have a rounded number of stars change it to be
while [ true ]; do cat /proc/loadavg | perl -ne 'm/(^[^ ]+)/; $L = $1; print "*" x $L; print " $L\n";' ; sleep 6; done
# Visual system load display It takes the first value of /prov/loadavg to print that many stars followed by the value.
while :;do rig |head -1 |tr '\n' ,;echo $RANDOM{,,,,} |tr -d ' ' ;done |sed -r -e 's/,(...)(..)(....).*/,\1-\2-\3/'
# "Infinite" data breach
# Process command output line by line in a while loop - This snippet allows to process the output of any bash command line by line.
while read -r line; do echo $line; done < <(YOUR COMMAND HERE);
while true ; do date | tr $'\n'' ' ; du -sh One/ ; sleep 1d ; done# Check the size of the 'One' directory once per date, prefixing the line with a timestamp. Using tr to turn the normal newline from date into a space.clear;look . |while read i;do echo "$i" |qrencode -o - -t UTF8 ; printf "%-20s""$i" |toilet -w $COLUMNS ;sleep 0.1 ;printf "\e[0;0H" ; done# qrcode "animation"while true; do printf "%s "$( date ); df -hP /share |grep /; sleep 10m; done# Poor person's filesystem time/space monitor in 10min increments. This was just a one off.s=5;while true; do [ $(($( date +%s ) % 600)) -le $s ] && end=$'\n' || end=$'\r' ; printf "\e[2K%s %s$end""$(date)""$(df -hP / | grep /)"; sleep $s; done# Show space and update current line every 5 seconds, but every 10 minutes move down a line and save history as you go.size=1 ; while ! stat conn.log ; do echo $size ; bro -e "redef encap_hdr_size=$size;" -r network-dump.pcap ; size=$((size+1)) ; done# Keep incrementing through a set of values until one is successful at creating a conn.log file. If it does not work will eventually need to Ctrl-C.while :;do iwlist wlan0 scan |awk -F\"'/ESSID/{print $2}' |espeak;done# Your Linux laptop says the ESSID names while you drive around.while :;do curl -Ls "X\.com"|md5sum;sleep 5m;done|awk '{if(NR>1&&l!=$1){system("echo the site changed|mail -s NOTIFY you@isp\.net");};l=$1}'#while sleep $(($RANDOM % 10)); do eject -T /dev/cdrom;sleep 0.1; done# If you have a cat and still have a cd/dvd/bluray rom drive, this keep a cat entertained for hours.while true ; do tmux next-window ; sleep 10; done# Auto switch through the current windows in your running tmux session.while [[ $(date +%Y) -ne 2019 ]];do figlet $(($(date -d 2019-01-01 +%s)-$(date +%s)));sleep 1;clear;done;figlet 'Happy New Year!'#countdownwhile :; do echo wub wub wub | espeak --stdout | play - pitch -400 bend .3,-600,.3 ; done# CLI generated dubstep. Shout out to # Alert me by email when a disconnected or unreachable server comes back onlinewhile ! ping -c1 the_host_down; do sleep 1; done && date | mail -s 'the host is back!' me@example.com
# Explanation: # ping -c1 host sends just one ping and exits with success or error.# while will keep running until the ping succeeds# When the ping succeeds the while loop will end, and an email will be sent with the date as the message# Limitations: # Depending on your system the parameter for sending a single ping might be different from -c1# Depending on your system the mail command might be different or work differently#==============================##==============================## CMD WHILE while-schleife#==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command while in a clear format. This allows users to quickly access the needed information for while without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for while are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the xcodebuild command with important options and switches using examples.
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command xcodebuild in a clear format. This allows users to quickly access the needed information for xcodebuild without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for xcodebuild are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the xctool command with important options and switches using examples.
# ██╗ ██╗ ██████╗████████╗ ██████╗ ██████╗ ██╗ # ╚██╗██╔╝██╔════╝╚══██╔══╝██╔═══██╗██╔═══██╗██║ # ╚███╔╝ ██║ ██║ ██║ ██║██║ ██║██║ # ██╔██╗ ██║ ██║ ██║ ██║██║ ██║██║ # ██╔╝ ██╗╚██████╗ ██║ ╚██████╔╝╚██████╔╝███████╗# ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝# xctool - Tool for building Xcode projects (Mac OS X)# Build a single project without any workspace:xctool -project YourProject.xcodeproj -scheme YourScheme build
# Build a project that is part of a workspace:xctool -workspace YourWorkspace.xcworkspace -scheme YourScheme build
# Clean, build and execute all the tests:xctool -workspace YourWorkspace.xcworkspace -scheme YourScheme clean build test
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command xctool in a clear format. This allows users to quickly access the needed information for xctool without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for xctool are a valuable resource to work efficiently and purposefully.
Editors are software applications used for writing and editing code and scripts. They provide features like syntax highlighting, code completion, and debugging tools to enhance productivity. Editors can range from simple text editors to complex integrated development environments (IDEs). They are essential for efficient coding and can be customized with plugins and extensions.
2.1 - 🖥️emacs
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the emacs command with important options and switches using examples.
# ███████╗███╗ ███╗ █████╗ ██████╗███████╗# ██╔════╝████╗ ████║██╔══██╗██╔════╝██╔════╝# █████╗ ██╔████╔██║███████║██║ ███████╗# ██╔══╝ ██║╚██╔╝██║██╔══██║██║ ╚════██║# ███████╗██║ ╚═╝ ██║██║ ██║╚██████╗███████║# ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚══════╝# Basic usage Indent Select text then press TAB
Cut CTRL-w
Copy ALT-w
Paste ("yank") CTRL-y
Search/Find CTRL-s
Replace ALT-% (ALT-SHIFT-5)
Save CTRL-x CTRL-s
Load/Open CTRL-x CTRL-f
Undo CTRL-x u
Highlight all text CTRL-x h
Directory listing CTRL-x d
Cancel a command CTRL-g
Font size bigger CTRL-x CTRL-+
Font size smaller CTRL-x CTRL--
# Buffers Split screen vertically CTRL-x 2 Split screen vertically with 5 row height CTRL-u 5 CTRL-x 2 Split screen horizontally CTRL-x 3 Split screen horizontally with 24 column width CTRL-u 24 CTRL-x 3 Revert to single screen CTRL-x 1 Hide the current screen CTRL-x 0 Kill the current screen CTRL-x k
Move to the next buffer CTRL-x O
Select a buffer CTRL-x b
Run command in the scratch buffer CTRL-x CTRL-e
# Other stuff Open a shell ALT-x eshell
Goto a line number ALT-x goto-line
Word wrap ALT-x toggle-word-wrap
Spell checking ALT-x flyspell-mode
Line numbers ALT-x linum-mode
Toggle line wrap ALT-x visual-line-mode
Compile some code ALT-x compile
List packages ALT-x package-list-packages
# Line numbers To add line numbers and enable moving to a line with CTRL-l:
(global-set-key "\C-l"'goto-line)
(add-hook 'find-file-hook (lambda () (linum-mode 1)))
# Basics C-x C-f "find" file i.e. open/create a file in buffer
C-x C-s save the file
C-x C-w write the text to an alternate name
C-x C-v find alternate file
C-x i insert file at cursor position
C-x b create/switch buffers
C-x C-b show buffer list
C-x k kill buffer
C-z suspend emacs
C-X C-c close down emacs
# Basic movement C-f forward char
C-b backward char
C-p previous line
C-n next line
M-f forward one word
M-b backward one word
C-a beginning of line
C-e end of line
C-v one page up
M-v scroll down one page
M-< beginning of text
M-> end of text
# Editing M-n repeat the following command n times
C-u repeat the following command 4 times
C-u n repeat n times
C-d delete a char
M-d delete word
M-Del delete word backwards
C-k kill line
# C-Space Set beginning mark (for region marking for example)
C-W "kill" (delete) the marked region
M-W copy the marked region
C-y "yank" (paste) the copied/killed region/line
M-y yank earlier text (cycle through kill buffer)
C-x C-x exchange cursor and mark
# C-t transpose two chars
M-t transpose two words
C-x C-t transpose lines
M-u make letters uppercase in word from cursor position to end
M-c simply make first letter in word uppercase
M-l opposite to M-u
# Important C-g quit the running/entered command
C-x u undo previous action
M-x revert-buffer RETURN
(insert like this) undo all changes since last save
M-x recover-file RETURN
Recover text from an autosave-file
M-x recover-session RETURN
if you edited several files
# Online-Help C-h c which command does this keystroke invoke
C-h k which command does this keystroke invoke and what does it do?
C-h l what were my last 100 typed keys
C-h w what key-combo does this command have?
C-h f what does this functiondo C-h v what\'s this variable and what is it\'s value
C-h b show all keycommands for this buffer
C-h t start the emacs tutorial
C-h i start the info reader
C-h C-k start up info reader and go to a certain key-combo point
C-h F show the emacs FAQ
C-h p show infos about the Elisp package on this machine
# Search/Replace C-s Search forward
C-r search backward
C-g return to where search started (if you are still in search mode)
M-% query replace
# Space or y replace this occurence
Del or n don\'t replace
. only replace this and exit (replace)
, replace and pause (resume with Space or y)
! replace all following occurences
^ back to previous match
RETURN or q quit replace
# Search/Replace with regular expressions# Characters to use in regular expressions: ^ beginning of line
$ end of line
. single char
.* group or null of chars
\< beginning of a word
\> end of a word
[] every char inside the backets (for example [a-z] means every small letter)
# M C-s RETURN search for regular expression forward
M C-r RETURN search for regular expression backward
M C-s incremental search
C-s repeat incremental search
M C-r incremental search backwards
C-r repeat backwards
M-x query-replace-regexp
search and replace
# Window-Commands C-x 2 split window vertically
C-x o change to other window
C-x 0 delete window
C-x 1 close all windows except the one the cursors in
C-x ^ enlarge window
M-x shrink-window
command says it ;-)
M C-v scroll other window
C-x 4 f find file in other window
C-x 4 o change to other window
C-x 40 kill buffer and window
C-x 52 make new frame
C-x 5 f find file in other frame
C-x 5 o change to other frame
C-x 50 close this frame
# Bookmark commands C-x r m set a bookmark at current cursor pos
C-x r b jump to bookmark
M-x bookmark-rename
M-x bookmark-delete
M-x bookmark-save
C-x r l list bookmarks
# d mark bookmark for deletion
r rename bookmark
s save all listed bookmarks
f show bookmark the cursor is over
m mark bookmarks to be shown in multiple window
v show marked bookmarks (or the one the cursor is over)
t toggle listing of the corresponding paths
w path to this file
x delete marked bookmarks
q quit bookmark list
# M-x bookmark-write
write all bookmarks in given file
M-x bookmark-load
load bookmark from given file
# Shell M-x shell starts shell modus
C-c C-c same as C-c under unix (stop running job)
C-d delete char forward
C-c C-d Send EOF
C-c C-z suspend job (C-z under unix)
M-p show previous commands
# DIRectory EDitor (dired) C-x d start up dired
C (large C) copy
d mark for erase
D delete right away
e or f open file or directory
g reread directory structure from file
G change group permissions (chgrp)
k delete line from listing on screen (don\'t actually delete)
m mark with *
n move to next line
o open file in other window and go there
C-o open file in other window but don\'t change there
P print file
q quit dired
Q do query-replace in marked files
R rename file
u remove mark
v view file content
x delete files marked with D
z compress file
M-Del remove all marks (whatever kind)
~ mark backup files (name~ files) for deletion
# mark auto-save files (#name#) for deletion */ mark directory with * (C-u * removes that mark again)
= compare this file with marked file
M-= compare this file with it\'s backup file
! apply shell command to this file
M-} change to the next file marked with * od D
M-{ change to the previous file marked with * od D
% d mark files described through regular expression for deletion
% m mark files described through regular expression for deletion (with *)
+ create directory
> changed to next dir
< change to previous dir
s toggle between sorting by name or date
# M-x speedbar starts up a separate window with a directory view
# Telnet M-x telnet starts up telnet-modus
C-d either delete char or send EOF
C-c C-c stop running job (similar to C-c under unix)
C-c C-d send EOF
C-c C-o clear output of last command
C-c C-z suspend execution of command
C-c C-u kill line backwards
M-p recall previous command
# Text# Works only in text mode M-s center line
M-S center paragraph
M-x center-region
# Macro-commands C-x ( start macro definition
C-x ) end of macro definition
C-x e execute last defined macro
M-n C-x e execute last defined macro n times
M-x name-last-kbd-macro
give name to macro (for saving)
M-x insert-keyboard-macro
save named macro into file
M-x load-file
load macro
M-x macroname
execute macroname
# Programming M C-\ indent region between cursor and mark
M-m move to first (non-space) char in this line
M-^ attach this line to previous
M-; formatize and indent comment
# C, C++ and Java Modes M-a beginning of statement
M-e end of statement
M C-a beginning of function M C-e end of function C-c RETURN Set cursor to beginning of function and mark at the end
C-c C-q indent the whole function according to indention style
C-c C-a toggle modus in which after electric signs (like {}:\';./*) emacs does the indention
C-c C-d toggle auto hungry mode in which emacs deletes groups of spaces with one del-press
C-c C-u go to beginning of this preprocessor statement
C-c C-c comment out marked area
# More general M-x outline-minor-mode
collapses function definitions in a file to a mere {...}
M-x show-subtree
If you are in one of the collapsed functions, this un-collapses it
# In order to achieve some of the feats coming up now you have to run etags *.c *.h *.cpp# (or what ever ending you source files have) in the source directory M-. (Meta dot) If you are in a function call, this will take you to it\'s definition
M-x tags-search ENTER
Searches through all you etaged
M-, (Meta comma) jumps to the next occurence for tags-search
M-x tags-query-replace yum.
This lets you replace some text in all the tagged files
# GDB (Debugger) M-x gdb starts up gdm in an extra window
# Version Control C-x v d show all registered files in this dir
C-x v = show diff between versions
C-x v u remove all changes since last checkin
C-x v ~ show certain version in different window
C-x v l print log
C-x v i mark file for version control add
C-x v h insert version control header into file
C-x v r check out named snapshot
C-x v s create named snapshot
C-x v a create changelog file in gnu-style
#==============================##==============================## CMD emacs ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command emacs in a clear format. This allows users to quickly access the needed information for emacs without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for emacs are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the libreoffice command with important options and switches using examples.
# ██╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ███████╗███████╗██╗ ██████╗███████╗# ██║ ██║██╔══██╗██╔══██╗██╔════╝██╔═══██╗██╔════╝██╔════╝██║██╔════╝██╔════╝# ██║ ██║██████╔╝██████╔╝█████╗ ██║ ██║█████╗ █████╗ ██║██║ █████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══╝ ██║ ██║██╔══╝ ██╔══╝ ██║██║ ██╔══╝ # ███████╗██║██████╔╝██║ ██║███████╗╚██████╔╝██║ ██║ ██║╚██████╗███████╗# ╚══════╝╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝# Convert documents to PDFlibreoffice --headless --convert-to pdf *.pptx
# Save them to a different directory?libreoffice --headless --convert-to pdf *.docx --outdir ~/docs/
# Convert files nested inside folders? # This uses sharkdp/fd, you could use GNU find, xargs etc.fd -e doc -e docx -x libreoffice --headless --convert-to pdf --outdir {//} {}
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command libreoffice in a clear format. This allows users to quickly access the needed information for libreoffice without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for libreoffice are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the nano command with important options and switches using examples.
# ███╗ ██╗ █████╗ ███╗ ██╗ ██████╗ # ████╗ ██║██╔══██╗████╗ ██║██╔═══██╗# ██╔██╗ ██║███████║██╔██╗ ██║██║ ██║# ██║╚██╗██║██╔══██║██║╚██╗██║██║ ██║# ██║ ╚████║██║ ██║██║ ╚████║╚██████╔╝# ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ # Howto Nano#----------------------#[ALT]+[X] = Menü Abschalten
[ALT]+[U] = Rückgängig
[STRG]+[C] = Abbrechen von Speichern, Öffnen Ersetzten usw
[ALT]+[E] = Erneut ausführen
[ALT]+[A] = Markieren
[ALT]+[6] = Kopieren
[STRG]+[U] = Einfügen
[STRG]+[K] = Ausschneiden und einfügen
[ALT]+[T] = Löscht den Text vom Curser bis Ende kann mit [STRG]+[U] wieder eingefügt werden
[STRG]+[W] = Suche
[ALT]+[W] = Weitersuchen
[ALT]+[R] = Suchen und Ersetzen
[STRG]+[S] = Speichern
[STRG]+[O] = Speichern unter
[STRG]+[X] = Exit
Einstellungen unter:
/etc/nanorc
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command nano in a clear format. This allows users to quickly access the needed information for nano without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for nano are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the vim command with important options and switches using examples.
# ██╗ ██╗██╗███╗ ███╗# ██║ ██║██║████╗ ████║# ██║ ██║██║██╔████╔██║# ╚██╗ ██╔╝██║██║╚██╔╝██║# ╚████╔╝ ██║██║ ╚═╝ ██║# ╚═══╝ ╚═╝╚═╝ ╚═╝# File management:e reload file
:q quit
:q! quit without saving changes
:w write file
:w {file} write new file
:x write file and exit
# Movement k
h l basic motion
j
w next start of word
W next start of whitespace-delimited word
e next end of word
E next end of whitespace-delimited word
b previous start of word
B previous start of whitespace-delimited word
0 start of line
$ end of line
gg go to first line in file
G go to end of file
gk move down one displayed line
gj move up one displayed line
# Insertion# To exit from insert mode use Esc or Ctrl-C# Enter insertion mode and:a append after the cursor
A append at the end of the line
i insert before the cursor
I insert at the beginning of the line
o create a new line under the cursor
O create a new line above the cursor
R enter insert mode but replace instead of inserting chars
:r {file} insert from file
# Editingu undo
yy yank (copy) a line
y{motion} yank text that {motion} moves over
p paste after cursor
P paste before cursor
<Del> or x delete a character
dd delete a line
d{motion} delete text that {motion} moves over
# Search and replace with the `:substitute` (aka `:s`) command:s/foo/bar/ replace the first match of 'foo' with 'bar' on the current line only
:s/foo/bar/g replace all matches (`g` flag) of 'foo' with 'bar' on the current line only
:%s/foo/bar/g replace all matches of 'foo' with 'bar' in the entire file (`:%s`)
:%s/foo/bar/gc ask to manually confirm (`c` flag) each replacement
# Preceding a motion or edition with a number repeats it 'n' times # Examples:50k moves 50 lines up
2dw deletes 2 words
5yy copies 5 lines
42G go to line 42#---------------------------------------------------------------------------------## VIM - Kurzanleitung von Christoph Maciejewski (c) 1999 ##---------------------------------------------------------------------------------## Allgemeines#-----------## Alle vim-Kommandos (beginnen mit ":") können in die Konfigurationsdatei eingetragen werden. Diese kann heissen: .gvimrc .vimrc oder unter Win32 _vimrc# Bearbeituns-Modi#----------------#[ESC]: Kommandomodus
[i]: Einfügemodus (an der aktuellen Stelle)
[A]: Einfügemodus (am Ende d er aktuellen Zeile -> "append")
[:]: Execute-modus (Eingabe eines Kommandos), Kommandovervollständigung mit [TAB]
# Dateiverwaltung:#----------------#[:e Dateiname]: Datei laden
[:e Verzeichnis]: Dateimanager (Der Parameter ist ein Verzeichnis)
[:w]:Aktuelle Datei speichern
[:w Dateiname]: Aktuelle Datei speichern unter einem neuen Namen (Bearbeitet wird we iter das Original)
[:sav Dateiname]: Aktuelle Datei speichern unter einem neuen Namen (Neue Datei wird bearbeitet)
[:buffer Dateiname]: Zwischen den Buffers (geöffnete Dateien) umschalten
[:next]: Zum nächsten Buffer wechseln
[:prev]: Zum vorherigen Buffer wechseln
[:q]:VIM beenden (nur wenn alle Buffers gespeichert, sonst Meldung)
[:q!]:VIM beenden (nicht gespeicherte Buffers gehen verloren)
[:wq]: Speichern und Schliessen (Alternativ: [ZZ])
# Editor:#-------#[u]: Aktion rückgängig machen (undo)
[Ctrl+r]: Aktion wiederherstellen (redo)
[yy]: Zeile kopieren
[dd]: Zeile ausschneiden (löschen)
[dw]: Wort ausschneiden (ab der aktuellen Position nach rechts)
[db]: Wort ausschneiden (ab der aktuellen Position nach links)
[d^]: Bis Zeilenanfang löschen (ab der aktuellen Position)
[d$]: Bis Zeilenende löschen (ab der aktuellen Position)
[:'a,'bd]: Von Marke "a" bis Marke "b" löschen
[p]: Einfügen
[v]: Anfang des zu markierenden Bereichs setzen (Mit den Cursortasten Bereich markieren)
[y]: Markierten Bereich kopieren
["xy]: Markierten Bereich in das Puffer "x" kopieren (es können bis zu 26 Puffer belegt werden)
["xp]: Text aus dem Puffer "x" einfügen
[VG]: Alles markieren (ab der aktuellen Position nach unten
[mx]: Marke setzen ("x" ist ein bel. Kleinbuchstabe -> es sind 26 Marken möglich)
['x]: Zur Marke "x" springen'[J]: CR/LF am Ende einer Zeile löschen (Zeilen zusammenfügen)
[:set list]: Nicht darstellbare Zeichen anzeigen
[:set ic]: Gross/Kleinschreibung ignorieren
[Ctrl+n]: Wort vervollständigen
[:%!xxd]: HEX-Editor-Modus (xxd muss installiert sein)
# Im Text navigieren:#-------------------#[gg]: An die erste Position des Textes springen
[GG]: An die letzte Position des Textes springen
[m][Cursor]: Um "m" Zeichen/Zeilen springen (mit den Cursortasten -> links, rechts, oben, unten)
[w]: Wortweise nach rechts springen (Mit [b] nach links) -> auch hier kann eine Zahl vorangestellt werden
# Suchen und Ersetzen:#--------------------#[/Suchwort]: Nach "Suchwort" suchen ("Suchwort" ist ein reg. Ausdruck). Mit [n] weiter suchen.
[/Suchwort/i]: Nach "Suchwort" suchen, Gross/Kleinschreibung ignorieren
[:1,$s/Unix/Linux/g]: "Unix" durch "Linux" ersetzen (Bereich: 1,$ -> vom Anfang bis Ende, g: Alle ersetzen)
[:1,.s/^/#/g]: Alle Zeilen bis zur aktuellen Cursorposition (.) auskommentieren
# Sonstiges: #----------#[:split]: Hauptfenster wird horizontal aufgespaltet. Wechseln mit [Ctrl+w+w].
[:r !date]: Ausgabe eines UNIX-Kommandos in den Text einfügen (hier Datum)
[:syntax on]: Syntaxeinfärbung einschalten
[:set nu!]: Zeilennummern ein-/ausblenden.
[:set ai]: Automatisches Einrücken (AutoIdent)
[:set cin]: Automatisches Einrücken im Still von C (Einrücken in Funktionsrümpfen)
[:set softtabstop=3]: Tabulator entspricht drei Leerzeichen
[:set shiftwidth=3]: Autom. Einrücken entsp richt drei Leerzeichen
[:ab w1 wort]: Autom. Ersetzen von "w1" durch "wort" während der Eingabe
#------------------------------------------------------------#:set scrolloff=5# Setup vim so that scrolling within a file will provide 5 lines of preceding context before the cursor.# Twitter Vimtips#------------------------------------------------------------#"+p
# to paste from it.
"+y
# to copy to the X11 (or Windows) clipboard."2p
# Will put the second to last thing yanked
"2p
# Will put the second to last thing yanked, "3p will put the third to last, etc.$ command | vim - (via @dlibanori)
# Edit a command output in Vim as a file%s/<C-R>a/bar/g
# will place the contents of register 'a' in the search, and replace it with 'bar'.%s/^ \ n/ /
# to delete all empty lines (remove spaces from command!)'.
# jumps to last modified line''0
# opens the last modified file ('1'2 '3 works too)
* # g* g# # each searches for the word under the cursor (forwards/backwards)/<CTRL-r><CTRL-w>
# will pull the word under the cursor into search./\%>80v.\+# with search highlighting (:set hlsearch) will highlight any text after column 80.5@a
# repeats it 5 times.:%s//joe/igc
# substitute your last search with joe.:%s/< !--\_.{-}-- >//
# Will delete HTML comments, potentially spanning multiple lines. (remove the spaces):%s/[.!?]\_s\+\a/\U&\E/g
# will uppercase the first letter of each sentence (except the very first one).:%s/\ r//g
# to remove all those nasty ^M from a file, or :%s/\ r$//g
# for only at the end of a line.:%s/\v(.*\n){5}/&\r# Will insert a blank line every 5 lines:40,50m30
# will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.:E to see a simple file explorer.
# (:Ex will too, if that is easier to remember.):Sex
# Will open a file explorer in a split window. I bet you will remember that one.:g/_pattern_/s/^/#/g
# will comment out lines containing _pattern_ (if '#' is your comment character/sequence):history
# lists the history of your recent commands, sans duplicates.:ju(mps) :
# list your movements {{help|jump-motions}}:ju(mps) :
# list your movements {{help|jump-motions}} \:ju(mps) : list your movements {{help|jump-motions}}
:s/\(.*\):\(.*\)/\2 : \1/
# Will reverse fields separated by ':':tabo
# will close all open tabs except the active one.:tabo
# Will close all open tabs except the active one.:vimgrep /stext/ **/*.txt | :copen
# searches for stext recursively in *.txt files and show results in separate window:vmap // y/< C-R >"< CR >
# "Will make searching for highlighted text (i.e. in visual mode) require only a highlight and //
:wa
# 'Will save all buffers.:y<line-number>
# Will yank the passed in ln, :y<ln1, ln2> will yank the range.< CTRL-n >< CTRL-p >
# offers word-completion while in insert mode.< CTRL-x >< CTRL-l >
# offers line completion in insert mode.<CTRL-i>
# trace your movements forwards in a file.<CTRL-o> :
# trace your movements backwards in a file.<CTRL-x><CTRL-l>
# offers line completion in insert mode.==
# Will auto-indent the current line. Select text in visual mode, then == to auto-indent the selected lines.@:
# to repeat the last executed command. http://is.gd/9cuP@a
# repeats the recording.@:
# repeats the last command-line command. So, :w then @: would write twice. Make sense? :h @: for more info!CTRL-w K
# Will switch vertical split into horizontal, CTRL-w H will switch a horizontal into a vertical.CTRL-w | and CTRL-W
# maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes 'em.:%s/<word>//gn
# Count the number of occurences of a word in a file with Ctrl-c
# to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)%s#.*\ (def\ ).*#\ 1#
# Will delete everything on all lines except for the string 'hours'. (no spaces)?http://somestuff.com
# To search for a URL without backslashing, search backwards! d% in #vim # Will delete to the matching brace. Makes sense, but never used it before. /cc [I (that is bracket-open, capital-i)
# shows lines containing the word under the cursor`.
# jumps to exact position of last modification.`ci " inside a ""
# Will erase everything between "" and place you in insertion mode."ci " inside a ""
# Will" erase everything between "" and place you in insertion mode. eg. :y41 or :y45,50
g//#
# will print the results of the last search w/ line numbersg;
# will cycle through your recent changes (or g, to go in reverse.g<CTRL-G>
# to see technical information about the file, such as how many words are in it, or how many bytes it is.gUU
# converts entire line to uppercase.ga
# will display the ASCII, hex, and octal value of the character under the cursor.ggVG=
# will auto-format the entire documentgq{movement}
# to wrap text, or just gq while in visual mode. gqap
# will format the current paragraph.guu
# converts entire line to lowercase.noremap ' ` and noremap ` '# to make marks easier to navigate. Now ` is easier to reach!q
# stops it.qa
# starts a recording in register 'a'.vim -c [command]
# will launch vim and run a : command at launch, e.g. "vim -c NERDTree."ysiw'
# 'to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
zz
# to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.~
# nverts case of current character."2p
# Will put the second to last thing yanked
"3p
# Will put the third to last, etc./< CTRL-r >< CTRL-w >
# Will pull the word under the cursor into search./\%>80v.\+ with search highlighting (:set hlsearch)
# Will highlight any text after column 80.:%s/<word>//gn
# Count the number of occurences of a word in a file with:%s//joe/igc
# substitute your last search with joe.:%s/[.!?]\_s\+\a/\U&\E/g
# Will uppercase the first letter of each sentence (except the very first one).:%s/\ r$//g
# for only at the end of a line.:%s/\ r//g
# to remove all those nasty ^M from a file, or:%s/\\/\//g
# Replaces all backslashes with forward slashes.:40,50m30
# Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.:E to see a simple file explorer. (:Ex
# Will too, if thats easier to remember.):Sex
# Will open a file explorer in a split window. I bet you'll remember that one.:history
# lists the history of your recent commands, sans duplicates.:ju(mps) :
# list your movements {{help|jump-motions}} \:s/\(.*\):\(.*\)/\2 : \1/
# Will reverse fields separated by ':':set foldmethod=syntax
# to make editing long files of code much easier. zo to open a fold. zc to close it.:set guifont=*
# in gvim or MacVim to get a font selection dialog. Useful while giving presentations.:vimgrep /stext/ **/*.txt | :copen
# searches for stext recursively in *.txt files and show results in separate window:vimgrep pattern **/*.txt
# Will search all *.txt files in the current directory and its subdirectories for the pattern.;
# is a motion to repeat last find with f. f'
# would find next quote.
c;
# would change up to the next '< CTRL-i >
# trace your movements forwards in a file.< CTRL-o > :
# trace your movements backwards in a file.< CTRL-x >< CTRL-l >
# offers line completion in insert mode.'f' and 't'# (like first and til) are very powerful. See :help t or :help f.Replaces all backslashes with forward slashes.
"_dd
# "to delete one line without overriding the buffer. "_ is black hole register. "When writing to this register, nothing happens.""g;
# Will cycle through your recent changes (or g, to go in reverse.g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is.
ga
# Will display the ASCII, hex, and octal value of the character under the cursor.git config --global core.editor "gvim --nofork"# to use gvim to edit your git messages set gits core editor as followsgq{movement}
# to wrap text, or just gq
# while in visual mode. gqap
# will format the current paragraph."+y
# "to copy to the X11 (or Windows) clipboard. "+p to paste from it.
"2p
# Will put the second to last thing yanked,%s/^ \ n/ / to delete all empty lines (remove spaces from command!)
* # g* g# each searches for the word under the cursor (forwards/backwards)/.*fred&.*joe/
# Will search for fred AND joe, in any order./< fred >/
# Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering)./\%>80v.\+ with search highlighting (:set hlsearch)
# Will highlight any text after column 80. /begin\_.*end
# Will search for begin AND end over multiple lines./fred\_s*joe/
# Will search for fred AND joe with whitespace (including newline) in between./fred|joe/
# Will search for either fred OR joe./joe.*fred.*bill/
# Will search for joe AND fred AND bill, in that order./joe/+3
# Will search for joe and place the cursor three lines below the match./joe/e
# Will search for joe and place the cursor at the end of the match.2f/
# would find the second occurrence of '/' in a line.40,50m30
# Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.:%s#.*(hours).*#1#
# Will delete everything on a line except for the string 'hours'.:%s/< ! - -\_.\{-}-- >//
# Will delete HTML comments, potentially spanning multiple lines. (remove the spaces):%s/^ \ n \{3}//
# Will delete a block of 3 empty lines. (remove the spaces):%s/joe|fred/jerks/g
# Will replace both 'fred' and 'joe' with 'jerks'.:%s/~/sue/igc
# substitute your last replacement string with sue.:40,50m30
# Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.:E to see a simple file explorer. (:Ex
# Will too, if thats easier to remember.):Sex
# Will open a file explorer in a split window. I bet you'll remember that one.:e $MYVIMRC# to directly edit your vimrc. :source $MYVIMRC# to reload. Mappings may make it even easier.:ju(mps) :
# list your movements {{help|jump-motions}} \:match ErrorMsg '\%>80v.\+'# uses matching to highlight lines longer than 80 columns.:r !date
# Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).:tab sball
# Will re-tab all files in the buffers list.:xa
# Will save all buffers and exit Vim.< CTRL-n >< CTRL-p >
# offers word-completion while in insert mode.< CTRL-o > :
# trace your movements backwards in a file. < CTRL-i >
# trace your movements forwards in a file.==
# Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.@:
# to repeat the last executed command.Ctrl-a, Ctrl-x
# Will increment and decrement, respectively, the number under the cursor.s"
# In visual mode, use to surround the selected text with " using the surround plugin.
In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for"+, "*
'\v'# Use in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.)[I
# (thats bracket-open, capital-i) shows lines containing the word under the cursorci " inside a ""
# "Will erase everything between "" and place you in insertion mode.
ggguG
# Will lower case the entire file (also known as the Jerry Yang treatment).gq{movement} to wrap text, or just gq while in visual mode. gqap
# Will format the current paragraph."+y
# "to copy to the X11 (or Windows) clipboard. "+p to paste from it.
"3p
# Will put the third to last, etc. http://is.gd/do1Dt* # g* g# # each searches for the word under the cursor (forwards/backwards)/< fred >/
# Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering)./begin\_.*end
# Will search for begin AND end over multiple lines./fred\_s*joe/
# Will search for fred AND joe with whitespace (including newline) in between./fred|joe/
# Will search for either fred OR joe./joe.*fred.*bill/
# Will search for joe AND fred AND bill, in that order./joe/+3
# Will search for joe and place the cursor three lines below the match./joe/e
# Will search for joe and place the cursor at the end of the match./joe/e+1
# Will search for joe and place the cursor at the end of the match, plus on character./joe/s-2
# Will search for joe and place the cursor at the start of the match, minus two characters.2f/
# would find the second occurrence of '/' in a line.:%s#<[^>]\+>##g
# Will remove HTML tags, leaving the text. (non-greedy):%s//joe/igc
# substitute your last search with joe.:%s/< ! - -\_.\{-}-- >//
# Will delete HTML comments, potentially spanning multiple lines. (remove the spaces):%s/[.!?]\_s\+\a/\U&\E/g
# Will uppercase the first letter of each sentence (except the very first one).:%s/^ \ n \{3}//
# Will delete a block of 3 empty lines. (remove the spaces):%s/^\ n\ +/\ r/
# Will compress multiple empty lines into one. (remove spaces):%s/joe|fred/jerks/g
# Will replace both 'fred' and 'joe' with 'jerks'.:g/search_term/#
# display each line containing 'search_term' with line numbers.:h slash< CTRL-d >
# to get a list of all help topics containing the word 'slash'.:history
# lists the history of your recent commands, sans duplicates.:lcd %:p:h
# Will change to the directory of the current file.:match ErrorMsg '\%>80v.\+'# uses matching to highlight lines longer than 80 columns.:r !date
# Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).:s/\(.*\):\(.*\)/\2 : \1/
# Will reverse fields separated by ':':set foldmethod=syntax
# to make editing long files of code much easier. zo to open a fold. zc to close it. :vimgrep pattern **/*.txt
# Will search all *.txt files in the current directory and its subdirectories for the pattern. :xa
# Will save all buffers and exit Vim.;
# is a motion to repeat last find with f. f' would find next quote. c;
# would change up to the next@:
# to repeat the last executed command. g-
g+
# After performing an undo, you can navigate through the changes using g- and g+ . Also, try :undolist to list the changes.'f'# first are very powerful. See :help f.'t'# til are very powerful. See :help t:%s/<word>//gn
# Count the number of occurences of a word in a file with q:
# Need to edit and run a previous command? then find the command, edit it, and Enter to execute the line.g;
# Will cycle through your recent changes (or g, to go in reverse.g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
gf
# Will open the file under the cursor. (Killer feature.)guu
# converts entire line to lowercase. gUU
# converts entire line to uppercase. ~
# inverts case of current character.$ command | vim -
/.*fred&.*joe/
# Will search for fred AND joe, in any order./< CTRL-r >< CTRL-w >
# Will pull the word under the cursor into search.:%s#<[^>]\+>##g
# Will remove HTML tags, leaving the text. (non-greedy):%s/\ r//g
# to remove all those nasty ^M from a file, or :%s/\ r$//g
# for only at the end of a line.:%s/^\ n\ +/\ r/
# Will compress multiple empty lines into one. (remove spaces):%s/~/sue/igc
# substitute your last replacement string with 'sue'.:e $MYVIMRC# to directly edit your vimrc. :source $MYVIMRC# to reload. Mappings may make it even easier.:g/_pattern_/s/^/#/g
# Will comment out lines containing _pattern_ (if '#' is your comment character/sequence):g/search_term/#
# display each line containing 'search_term' with line numbers.:lcd %:p:h
# Will change to the directory of the current file.:set guifont=*
# in gvim or MacVim to get a font selection dialog. Useful while giving presentations.:tab sball
# Will re-tab all files in the buffers list.:vimgrep /stext/ **/*.txt | :copen
:w !sudo tee %
# Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?):wa
# Will save all buffers.< CTRL-x >< CTRL-l >
# offers line completion in insert mode.CTRL-w H
# Will switch a horizontal into a vertical.CTRL-w K
# Will switch vertical split into horizontalCTRL-w s CTRL-w T
# Will open current buffer in new tabCTRL-w | and CTRL-W _
# maximize your current split vertically and horizontally, respectively. CTRL-W =
# equalizes em.Ctrl-a, Ctrl-x
# Will increment and decrement, respectively, the number under the cursor.vim -x filename
# Edit and encrypt a filevim scp://username@host//path/to/file
# From a command-line, to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)K
# runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.q:
# Need to edit and run a previous command? then find the command, edit it, and Enter to execute the line. ga
# Will display the ASCII, hex, and octal value of the character under the cursor.gf
# Will open the file under the cursor. (Killer feature.)ggVG=
# Will auto-format the entire documentggguG
# Will lower case the entire file (also known as the Jerry Yang treatment).git config --global core.editor "gvim --nofork"# searches for stext recursively in *.txt files and show results in separate windowvim -c [command]
# to use gvim to edit your git messages set gits core editor. Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."zz
# to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.%s/<C-R>a/bar/g
# Will place the contents of register 'a' in the search, and replace it with 'bar'.'0
# opens the last modified file ('1'2 '3 works too)
:%s#.*(hours).*#1#
# Will delete everything on a line except for the string 'hours'.Ctrl-c
# to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)qa
# starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.:%s/\ v(.*\ n){5}/&\ r
# Will insert a blank line every 5 lines (remove spaces):read [filename]
# Will insert the contents of [filename] at the current cursor position:tabdo [some command]
# Will execute the command in all tabs. Also see windo, bufdo, argdo.Ctrl+r=53+17<Enter>.
# In insert mode: This way you can do some calcs with vim.'u'# is undo. Ctrl-R
# is redo?ci{ ▒
# change text inside {} block. Also see di{, yi{, ci( etc.%
# matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.%
# matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!:scriptnames
# Will list all plugins and _vimrcs loaded.:set autochdir instead of :lcd %:p:h
# in your vimrc to change directories upon opening a file.:vsplit filename
# Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!# Twitter Vimtips *vimtips.txt* For Vim version 8.0. http://zzapper.co.uk/vimtips.html Jul2017#------------------------------------------------------------#------------------------------------------------------------------------------
# new items marked [N] , corrected items marked [C]# *best-searching*/joe/e : cursor set to End of match
3/joe/e+1 : find 3rd joe cursor set to End of match plus 1 [C]
/joe/s-2 : cursor set to Start of match minus 2/joe/+3 : find joe move cursor 3 lines down
/^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line)
/^[A-J]/ : search for lines beginning with one or more A-J
/begin\_.*end : search over possible multiple lines
/fred\_s*joe/ : any whitespace including newline [C]
/fred\|joe : Search for FRED OR JOE
/.*fred\&.*joe : Search for FRED AND JOE in any ORDER!
/\<fred\>/ : search for fred but not alfred or frederick [C]
/\<\d\d\d\d\> : Search for exactly 4 digit numbers
/\D\d\d\d\d\D : Search for exactly 4 digit numbers
/\<\d\{4}\> : same thing
/\([^0-9]\|^\)%.*% : Search for absence of a digit or beginning of line
# finding empty lines/^\n\{3} : find 3 empty lines
/^str.*\nstr : find 2 successive lines starting with str
/\(^str.*\n\)\{2} : find 2 successive lines starting with str
# using rexexp memory in a search find fred.*joe.*joe.*fred *C*/\(fred\).*\(joe\).*\2.*\1# Repeating the Regexp (rather than what the Regexp finds)/^\([^,]*,\)\{8}
# visual searching:vmap // y/<C-R>"<CR> : search for visually highlighted text
:vmap <silent> // y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR> : with spec chars
# \zs and \ze regex delimiters :h /\zs/<\zs[^>]*\ze> : search for tag contents, ignoring chevrons
# zero-width :h /\@=/<\@<=[^>]*>\@= : search for tag contents, ignoring chevrons
/<\@<=\_[^>]*>\@= : search for tags across possible multiple lines
# searching over multiple lines \_ means including newline/<!--\_p\{-}--> : search for multiple line comments
/fred\_s*joe/ : any whitespace including newline *C*
/bugs\(\_.\)*bunny : bugs followed by bunny anywhere in file
:h \_ : help
# search for declaration of subroutine/function under cursor:nmap gx yiw/^\(sub\<bar>function\)\s\+<C-R>"<CR>
#" multiple file search
:bufdo /searchstr/ : use :rewind to recommence search
# multiple file search better but cheating:bufdo %s/searchstr/&/gic : say n and then a to stop
# How to search for a URL without backslashing?http://www.vim.org/ : (first) search BACKWARDS!!! clever huh!
# Specify what you are NOT searching for (vowels)/\c\v([^aeiou]&\a){4} : search for4 consecutive consonants
/\%>20l\%<30lgoat : Search for goat between lines 20 and 30 [N]
/^.\{-}home.\{-}\zshome/e : match only the 2nd occurence in a line of "home" [N]
:%s/home.\{-}\zshome/alone : Substitute only the 2nd occurrence of home in any line [U]
# find str but not on lines containing tongue^\(.*tongue.*\)\@!.*nose.*$
\v^((tongue)@!.)*nose((tongue)@!.)*$
.*nose.*\&^\%(\%(tongue\)\@!.\)*$
:v/tongue/s/nose/&/gic
'a,'bs/extrascost//gc : trick: restrict search to between markers (answer n) [N]
/integ<C-L> : Control-L to complete search term [N]
#----------------------------------------# *best-substitution*:%s/fred/joe/igc : general substitute command
:%s//joe/igc : Substitute what you last searched for [N]
:%s/~/sue/igc : Substitute your last replacement string [N]
:%s/\r//g : Delete DOS returns ^M
# Is your Text File jumbled onto one line? use following:%s/\r/\r/g : Turn DOS returns ^M into real returns
:%s= *$== : delete end of line blanks
:%s= \+$== : Same thing
:%s#\s*\r\?$## : Clean both trailing spaces AND DOS returns:%s#\s*\r*$## : same thing# deleting empty lines:%s/^\n\{3}// : delete blocks of 3 empty lines
:%s/^\n\+/\r/ : compressing empty lines
:%s#<[^>]\+>##g : delete html tags, leave text (non-greedy)
:%s#<\_.\{-1,}>##g : delete html tags possibly multi-line (non-greedy)
:%s#.*\(\d\+hours\).*#\1# : Delete all but memorised string (\1) [N]# parse xml/soap %s#><\([^/]\)#>\r<\1#g : split jumbled up XML file into one tag per line [N]%s/</\r&/g : simple split of html/xml/soap [N]
:%s#<[^/]#\r&#gic : simple split of html/xml/soap but not closing tag [N]:%s#<[^/]#\r&#gi : parse on open xml tag [N]:%s#\[\d\+\]#\r&#g : parse on numbered array elements [1] [N]ggVGgJ : rejoin XML without extra spaces (gJ) [N]
%s=\\n#\d=\r&=g : parse PHP error stack [N]
:%s#^[^\t]\+\t## : Delete up to and including first tab [N]# VIM Power Substitute:'a,'bg/fred/s/dick/joe/igc : VERY USEFUL
# duplicating columns:%s= [^ ]\+$=&&= : duplicate end column
:%s= \f\+$=&&= : Dupicate filename
:%s= \S\+$=&& : usually the same
# memory:%s#example#& = &#gic : duplicate entire matched string [N]:%s#.*\(tbl_\w\+\).*#\1# : extract list of all strings tbl_* from text [NC]:s/\(.*\):\(.*\)/\2 : \1/ : reverse fields separated by :
:%s/^\(.*\)\n\1$/\1/ : delete duplicate lines
:%s/^\(.*\)\(\n\1\)\+$/\1/ : delete multiple duplicate lines [N]
# non-greedy matching \{-}:%s/^.\{-}pdf/new.pdf/ : delete to 1st occurence of pdf only (non-greedy)
%s#^.\{-}\([0-9]\{3,4\}serial\)#\1#gic : delete up to 123serial or 1234serial [N]# use of optional atom \?:%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc : lowercase with optional leading characters# over possibly many lines:%s/<!--\_.\{-}-->// : delete possibly multi-line comments
:help /\{-} : help non-greedy
# substitute using a register:s/fred/<c-r>a/g : sub fred# with contents of register "a":s/fred/<c-r>asome_text<c-r>s/g
:s/fred/\=@a/g : better alternative as register not displayed (not *) [C]
:s/fred/\=@*/g : replace string with contents of paste register [N]
# multiple commands on one line:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/
:%s/a/but/gie|:update|:next : then use @: to repeat
# ORing:%s/goat\|cow/sheep/gc : ORing (must break pipe)
:'a,'bs#\[\|\]##g : remove [] from lines between markers a and b [N]:%s/\v(.*\n){5}/&\r : insert a blank line every 5 lines [N]
# Calling a VIM function:s/__date__/\=strftime("%c")/ : insert datestring
:inoremap \zd <C-R>=strftime("%d%b%y")<CR> : insert date eg 31Jan11 [N]
# Working with Columns sub any str1 in col3:%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:
# Swapping first & last column (4 columns):%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:
# format a mysql query :%s#\<from\>\|\<where\>\|\<left join\>\|\<\inner join\>#\r&#g# filter all form elements into paste register:redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END
:nmap ,z :redir @*<Bar>sil exec 'g@<\(input\<Bar>select\<Bar>textarea\<Bar>/\=form\)\>@p'<Bar>redir END<CR>
# substitute string in column 30 [N]:%s/^\(.\{30\}\)xx/\1yy/
# decrement numbers by 3:%s/\d\+/\=(submatch(0)-3)/
# increment numbers by 6 on certain lines only:g/loc\|function/s/\d/\=submatch(0)+6/
# better:%s#txtdev\zs\d#\=submatch(0)+1#g:h /\zs
# increment only numbers gg\d\d by 6 (another way):%s/\(gg\)\@<=\d\+/\=submatch(0)+6/
:h zero-width
# rename a string with an incrementing number:let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1 # convert yy to 10,11,12 etc# as above but more precise:let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,xx13# find replacement text, put in memory, then use \zs to simplify substitute:%s/"\([^.]\+\).*\zsxx/\1/
# "Pull word under cursor into LHS of a substitute
:nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>## Pull Visually Highlighted text into LHS of a substitute:vmap <leader>z :<C-U>%s/\<<c-r>*\>/
# substitute singular or plural:'a,'bs/bucket\(s\)*/bowl\1/gic [N]
----------------------------------------
# all following performing similar task, substitute within substitution# Multiple single character substitution in a portion of line only:%s,\(all/.*\)\@<=/,_,g : replace all / with _ AFTER "all/"# Same thing:s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')## Substitute by splitting line, then re-joining:s#all/#&^M#|s#/#_#g|-j!
# Substitute inside substitute:%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/
----------------------------------------
# *best-global* command :g/gladiolli/# : display with line numbers (YOU WANT THIS!)
:g/fred.*joe.*dick/ : display all lines fred,joe & dick
:g/\<fred\>/ : display all lines fred but not freddy
:g/^\s*$/d : delete all blank lines
:g!/^dd/d : delete lines not containing string
:v/^dd/d : delete lines not containing string
:g/joe/,/fred/d : not line based (very powerfull)
:g/fred/,/joe/j : Join Lines [N]
:g/-------/.-10,.d : Delete string & 10 previous lines
:g/{/ ,/}/- s/\n\+/\r/g : Delete empty lines but only between {...}
:v/\S/d : Delete empty lines (and blank lines ie whitespace)
:v/./,/./-j : compress empty lines
:g/^$/,/./-j : compress empty lines
:g/<input\|<form/p : ORing
:g/^/put_ : double space file (pu = put)
:g/^/m0 : Reverse file (m = move)
:g/^/m$ : No effect! [N]
:'a,'bg/^/m'b : Reverse a section a to b
:g/^/t. : duplicate every line
:g/fred/t$ : copy (transfer) lines matching fred to EOF
:g/stage/t'a : copy (transfer) lines matching stage to marker a (cannot use .) [C]
:g/^Chapter/t.|s/./-/g : Automatically underline selecting headings [N]
:g/\(^I[^^I]*\)\{80}/d : delete all lines containing at least 80 tabs
# perform a substitute on every other line:g/^/ if line('.')%2|s/^/zz /
# match all lines containing "somestr" between markers a & b# copy after line containing "otherstr":'a,'bg/somestr/co/otherstr/ : co(py) or mo(ve)
# as above but also do a substitution:'a,'bg/str1/s/str1/&&&/|mo/str2/
:%norm jdd : delete every other line
# incrementing numbers (type <c-a> as 5 characters):.,$g/^\d/exe "norm! \<c-a>": increment numbers
:'a,'bg/\d\+/norm! ^A : increment numbers
# storing glob results (note must use APPEND) you need to empty reg a first with qaq. # save results to a register/paste buffer:g/fred/y A : append all lines fred to register a
:g/fred/y A | :let @*=@a : put into paste buffer
:g//y A | :let @*=@a : put last glob into paste buffer [N]
:let @a=''|g/Barratt/y A |:let @*=@a
# filter lines to a file (file must already exist):'a,'bg/^Error/ . w >> errors.txt
# duplicate every line in a file wrap a print '' around each duplicate:g/./yank|put|-1s/'/"/g|s/.*/Print '&'/
# replace string with contents of a file, -d deletes the "mark"':g/^MARK$/r tmp.txt | -d
# display prettily:g/<pattern>/z#.5 : display with context
:g/<pattern>/z#.5|echo "==========" : display beautifully
# Combining g// with normal mode commands:g/|/norm 2f|r* : replace 2nd | with a star
"send output of previous global command to a new window
:nmap <F3> :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>
"----------------------------------------
# *Best-Global-combined-with-substitute* (*power-editing*):'a,'bg/fred/s/joe/susan/gic : can use memory to extend matching
:/fred/,/joe/s/fred/joe/gic : non-line based (ultra)
:/biz/,/any/g/article/s/wheel/bucket/gic: non-line based [N]
----------------------------------------
# Find fred before beginning search f################################################################# In Vim mehrere Zeilen auskommentieren#------------------------------------------------------------#[STRG]+[V]
um in den „block-visual mode“ zu gelangen
Gewünschte Zeilen (mit den Pfeiltasten) markieren
[SHIFT]+[i] drücken um ein Zeichen am Anfang der Zeile einzufügen
Das Kommentarzeichen einfügen (z.B. „#“ oder „//“)
Mit [ESC] den visuellen Modus beenden.
Nun sollte vor jeder Zeile die man gerade markiert hatte das Zeichen erscheinen.
# KommentierenDazu Wechselt man zuerst in den “Visuellen-Block-Modus” mit STRG+V
Und markiert nun abwärts die Zeilen die man kommentieren möchte (Pfeil nach unten oder j)
Sind alle gewünschten Zeilen markiert wechselt man mit SHIFT+I in den “Insert-Modus”.
Nun schreibt man an den Anfang der obersten Zeile eine Kommentarzeichen (z.B # für Bash) und verlässt dann den “Insert-Modus”.Nun werden an den Anfang jeder markierten Zeile eine # eingefügt.# Ent-KommentierenDazu Wechselt man zuerst in den “Visuellen-Block-Modus” mit STRG+V
Und markiert nun abwärts die Rauten die man entfernen möchte (Pfeil nach unten oder j)
Sind alle gewünschten Rauten markiert entfernt man sie mit ‘x’
########################### vim bash-support plugin ##################################:helptags $HOME/.vim/doc/
# Make Bash-support Plug-in Help Accessible\hh
# for built-in help\hm
# for a command help\ntw
# Start settings \cfr
# insert Comments in .sh scripts\sc
# case in … esac (n, I)\sei
# elif then (n, I)\sf
# for in do done (n, i, v)\sfo
# for ((…)) do done (n, i, v)\si
# if then fi (n, i, v)\sie
# if then else fi (n, i, v)\ss
# select in do done (n, i, v)\su
# until do done (n, i, v)\sw
# while do done (n, i, v)\sfu
# function (n, i, v)\se
# echo -e “…” (n, i, v)\sp
# printf “…” (n, i, v)\sa
# array element, ${.[.]} (n, i, v) and many more array features.\cfu
# To create a header for the function above, type \cfu\rr
# update file, run script (n, I)\ra
# set script cmd line arguments (n, I)\rc
# update file, check syntax (n, I)\rco
# syntax check options (n, I)\rd
# start debugger (n, I)\re
# make script executable/not exec.(*) (in)\nr
# to write predefined code snippets\nw
# to read predefined code snippets################### vim NERDTree plugin #########################:NERDTree
# start NERDTree# in vim you can a number under the cursor, or nearest number # - press strg-a to increment# - press strl-x to decrementvim +/search-term <filename>
# will go to the first match of the specified search term# A vi/vim 'feature'. I found this years ago, by accident: If in vi command mode you type!!command # NOTE: no preceding colon!# then vi will run command and put its output into the file being edited, eg:!!ls -l
# How to add text at the end of each line - This will do it to every line in the file::%s/$/,/
# If you want to do a subset of lines instead of the whole file, you can specify them in place of the %.# One way is to do a visual select and then type the :. It will fill in :'<,'> for you, then you type the rest of it (Notice you only need to add s/$/,/):'<,'>s/$/,/
# There is in fact a way to do this using Visual block mode. Simply pressing $A in Visual block mode appends to the end of all lines in the selection. The appended text will appear on all lines as soon as you press Esc.# So this is a possible solution:vip<C-V>$A,<Esc>
vi tip: pressing '.' in command mode will repeat the last change made (insert, append, delete, etc.). Can be prefixed with number.
In vim, pressing % while the cursor is over a {, ( or [ will jump your cursor to the matching ], ), or } and vice versa.
gq{movement} # to wrap text, or just gq while in visual mode. gqap will format the current paragraph.g<CTRL-G> # to see technical information about the file, such as how many words are in it, or how many bytes it is.:%s/[.!?]\_s\+\a/\U&\E/g # will uppercase the first letter of each sentence (except the very first one). :g/_pattern_/s/^/#/g # will comment out lines containing _pattern_ (if '#' is your comment character/sequence):vimgrep /stext/ **/*.txt | :copen # searches for stext recursively in *.txt files and show results in separate window%s/^ \ n/ / # to delete all empty lines (remove spaces from command!) ggVG= # will auto-format the entire document:tabo # will close all open tabs except the active one./\%>80v.\+# with search highlighting (:set hlsearch) will highlight any text after column 80.gq{movement} # to wrap text, or just gq while in visual mode. gqap will format the current paragraph.:vimgrep /stext/ **/*.txt | :copen # searches for stext recursively in *.txt files and show results in separate windowTo search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
In gvim, change the cursor depending on what mode you are in (normal, insert, etc):
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
CTRL-w | and CTRL-W # maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes 'em./<CTRL-r><CTRL-w> # will pull the word under the cursor into search."+y to copy to the X11 (or Windows) clipboard. "+p to paste from it.
ga # will display the ASCII, hex, and octal value of the character under the cursor. [I (that is bracket-open, capital-i) # shows lines containing the word under the cursor % matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:40,50m30 # will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for"+, "*
vim -c [command] # will launch vim and run a : command at launch, e.g. "vim -c NERDTree." g; # will cycle through your recent changes (or g, to go in reverse. '0 # opens the last modified file ('1'2 '3 works too)
qa # starts a recording in register 'a'. q # stops it. @a # repeats the recording. 5@a # repeats it 5 times. g//# # will print the results of the last search w/ line numbers %s/<C-R>a/bar/g # will place the contents of register 'a' in the search, and replace it with 'bar'.:%s/~/sue/igc substitute your last replacement string with sue.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':' :%s/~/sue/igc substitute your last replacement string with 'sue'.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
Edit and encrypt a file: vim -x filename (via @dlibanori)
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns.
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
/.*fred&.*joe/ # Will search for fred AND joe, in any order. gf # Will open the file under the cursor. (Killer feature.) /joe/e # Will search for joe and place the cursor at the end of the match. @: to repeat the last executed command.
:read [filename] # Will insert the contents of [filename] at the current cursor position :e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) /joe/+3 # Will search for joe and place the cursor three lines below the match. Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
CTRL-w s CTRL-w T # Will open current buffer in new tab :Sex # Will open a file explorer in a split window. I bet you will remember that one. < CTRL-n >< CTRL-p > offers word-completion while in insert mode.
git config --global core.editor "gvim --nofork"# to use gvim to edit your git messages set gits core editor as follows:CTRL-w K # Will switch vertical split into horizontal, CTRL-w H will switch a horizontal into a vertical. :%s/\\/\//g # Replaces all backslashes with forward slashes.ysiw' # to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin':E to see a simple file explorer. # (:Ex will too, if that is easier to remember.):%s/\ r//g # to remove all those nasty ^M from a file, or :%s/\ r$//g # for only at the end of a line.'. # jumps to last modified line'`. # jumps to exact position of last modification.`:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). guu # converts entire line to lowercase. gUU # converts entire line to uppercase. ~ # nverts case of current character.From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
noremap ' ` and noremap ` '# to make marks easier to navigate. Now ` is easier to reach'! :wa # Will save all buffers. :xa # Will save all buffers and exit Vim.:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) :history # lists the history of your recent commands, sans duplicates.:scriptnames # Will list all plugins and _vimrcs loaded. :%s/<word>//gn # Count the number of occurences of a word in a file with :vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!<CTRL-x><CTRL-l> # offers line completion in insert mode."2p # Will put the second to last thing yanked
"3p # Will put the third to last, etc.:ju(mps) : # list your movements {{help|jump-motions}} In visual mode, use s" to surround the selected text with " using the surround plugin.
:%s//joe/igc # substitute your last search with joe. You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:set guifont=* # in gvim or MacVim to get a font selection dialog. Useful while giving presentations. :%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) == # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.2f/ would find the second occurrence of '/' in a line.
:lcd %:p:h # Will change to the directory of the current file. In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) <CTRL-o> : # trace your movements backwards in a file. <CTRL-i> # trace your movements forwards in a file.* # g* g# # each searches for the word under the cursor (forwards/backwards)Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
/begin\_.*end # Will search for begin AND end over multiple lines. Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.)
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) :%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) /fred|joe/ # Will search for either fred OR joe. :h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
Use "_dd to delete one line without overriding the buffer. "_ is black hole register. "When writing to this register, nothing happens."/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. :tab sball # Will re-tab all files in the buffers list. $ command | vim - (via @dlibanori) # Edit a command output in Vim as a fileci{ â change text inside {} block. Also see di{, yi{, ci( etc.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. :tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. :%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. /fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. /joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. :r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). :g/search_term/# display each line containing 'search_term' with line numbers.
ci " inside a "" # Will erase everything between "" and place you in insertion mode."/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).:ju(mps) : # list your movements {{help|jump-motions}} \:%s/\ r//g # to remove all those nasty ^M from a file, or :%s/\ r$//g # for only at the end of a line.< CTRL-x >< CTRL-l > offers line completion in insert mode.
/begin\_.*end # Will search for begin AND end over multiple lines. < CTRL-n >< CTRL-p > offers word-completion while in insert mode.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.)
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80.To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines."+y to copy to the X11 (or Windows) clipboard. "+p to paste from it.
/.*fred&.*joe/ # Will search for fred AND joe, in any order. :tab sball # Will re-tab all files in the buffers list. :vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree." ggVG= # Will auto-format the entire document:Sex # Will open a file explorer in a split window. I bet you'll remember that one. :%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) :scriptnames # Will list all plugins and _vimrcs loaded. :vimgrep /stext/ **/*.txt | :copen # searches for stext recursively in *.txt files and show results in separate window qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is.
Edit and encrypt a file: vim -x filename (via @dlibanori)
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. ysiw' # 'to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
g; # Will cycle through your recent changes (or g, to go in reverse. /< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) %s/^ \ n/ / # to delete all empty lines (remove spaces from command!) :history lists the history of your recent commands, sans duplicates.
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
"2p # Will put the second to last thing yanked, "3p will put the third to last, etc.
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). :tabo # Will close all open tabs except the active one.:set guifont=* # in gvim or MacVim to get a font selection dialog. Useful while giving presentations. Ctrl-c # to quickly get out of command-line mode. (Faster than hitting ESC a couple times.) :%s/<word>//gn # Count the number of occurences of a word in a file with < CTRL-o > : # trace your movements backwards in a file. < CTRL-i > # trace your movements forwards in a file.guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.)You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:g/search_term/# display each line containing 'search_term' with line numbers.
git config --global core.editor "gvim --nofork"# to use gvim to edit your git messages set gits core editor as follows:'0 opens the last modified file ('1'2 '3 works too)
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) :tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more
ga # Will display the ASCII, hex, and octal value of the character under the cursor. [I (that is bracket-open, capital-i) shows lines containing the word under the cursor
2f/ would find the second occurrence of '/' in a line.
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one). ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.In gvim, change the cursor depending on what mode you are in (normal, insert, etc):
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next 'gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph./joe/e # Will search for joe and place the cursor at the end of the match. * # g* g# each searches for the word under the cursor (forwards/backwards):e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).CTRL-w K # Will switch vertical split into horizontalCTRL-w H # Will switch a horizontal into a vertical. CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for"+, "*
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. :%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':' :%s//joe/igc substitute your last search with joe.
@: to repeat the last executed command.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
/fred|joe/ # Will search for either fred OR joe. :%s/~/sue/igc substitute your last replacement string with sue.
gf # Will open the file under the cursor. (Killer feature.) ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
CTRL-w s CTRL-w T # Will open current buffer in new tab K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. :lcd %:p:h # Will change to the directory of the current file. :set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
:read [filename] # Will insert the contents of [filename] at the current cursor position :wa # Will save all buffers. :xa # Will save all buffers and exit Vim.Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
noremap ' ` and noremap ` '# to make marks easier to navigate. Now ` is easier to reach! /joe/+3 # Will search for joe and place the cursor three lines below the match. Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
:%s/\\/\//g # Replaces all backslashes with forward slashes./joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. :%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) ci " inside a "" # "Will erase everything between "" and place you in insertion mode.
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) :g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence) In visual mode, use s" to surround the selected text with " using the surround plugin.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. :w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) :%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. :ju(mps) : list your movements {{help|jump-motions}} \
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
Edit and encrypt a file: vim -x filename (via @dlibanori)
2f/ would find the second occurrence of '/' in a line.
:lcd %:p:h # Will change to the directory of the current file.
Count the number of occurences of a word in a file with :%s/<word>//gn
g; # Will cycle through your recent changes (or g, to go in reverse.
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
@: to repeat the last executed command.
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
/fred|joe/ # Will search for either fred OR joe.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
* # g* g# each searches for the word under the cursor (forwards/backwards)
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
In visual mode, use s" to surround the selected text with " using the surround plugin.
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next '
:Sex # Will open a file explorer in a split window. I bet you'll remember that one.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. :g/search_term/# display each line containing 'search_term' with line numbers.
"2p # Will put the second to last thing yanked,
"3p # Will put the third to last, etc.:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern.:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) :vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) ci " inside a "" # Will" erase everything between "" and place you in insertion mode.
CTRL-w K # Will switch vertical split into horizontalCTRL-w H # Will switch a horizontal into a vertical. In gvim, change the cursor depending on what mode you are in (normal, insert, etc):
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. :%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one). [I (that is bracket-open, capital-i) shows lines containing the word under the cursor
:read [filename] # Will insert the contents of [filename] at the current cursor position :%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) /\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80.zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.:%s//joe/igc substitute your last search with joe.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph.:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more
:%s/\\/\//g
Replaces all backslashes with forward slashes.
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. :%s/~/sue/igc substitute your last replacement string with 'sue'.
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
ga # Will display the ASCII, hex, and octal value of the character under the cursor. :match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns.
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
'0 opens the last modified file ('1'2 '3 works too)
/joe/e # Will search for joe and place the cursor at the end of the match. :vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence) :E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.):r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). == # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'."+y to copy to the X11 (or Windows) clipboard. "+p to paste from it.
:wa # Will save all buffers. :xa # Will save all buffers and exit Vim.g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is.
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
CTRL-w s CTRL-w T # Will open current buffer in new tab :vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
:tab sball # Will re-tab all files in the buffers list. gf # Will open the file under the cursor. (Killer feature.) You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) < CTRL-n >< CTRL-p > offers word-completion while in insert mode.
:scriptnames # Will list all plugins and _vimrcs loaded. In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for"+, "*
/begin\_.*end # Will search for begin AND end over multiple lines. Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.)
:history lists the history of your recent commands, sans duplicates.
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
< CTRL-o > : # trace your movements backwards in a file. < CTRL-i > # trace your movements forwards in a file.< CTRL-x >< CTRL-l > # offers line completion in insert mode.ggVG= # Will auto-format the entire document/joe/+3 # Will search for joe and place the cursor three lines below the match. :%s/~/sue/igc substitute your last replacement string with sue.
Use "_dd to delete one line without overriding the buffer. "_ is black hole register. "When writing to this register, nothing happens."%s/^ \ n/ / to delete all empty lines (remove spaces from command!)
Sorry, everyone, for the extended absence. I hope to return to tweeting on a regular schedule shortly. The site will be back, too.
:scriptnames # Will list all plugins and _vimrcs loaded. noremap ' ` and noremap ` ' to make marks easier to navigate. Now ` is easier to reach!`[I (that is bracket-open, capital-i) shows lines containing the word under the cursor
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) '0 opens the last modified file ('1'2 '3 works too)
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
gf # Will open the file under the cursor. (Killer feature.) Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree." % matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence) CTRL-w K # Will switch vertical split into horizontalCTRL-w H # Will switch a horizontal into a vertical. :set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
ci " inside a "" # "Will erase everything between "" and place you in insertion mode.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.:lcd %:p:h # Will change to the directory of the current file. :%s/\\/\//g
Replaces all backslashes with forward slashes.
:ju(mps) : list your movements {{help|jump-motions}} \
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) < CTRL-x >< CTRL-l > offers line completion in insert mode.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. :vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
:g/search_term/# display each line containing 'search_term' with line numbers.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). :h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
/joe/e # Will search for joe and place the cursor at the end of the match. /fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. CTRL-w s CTRL-w T # Will open current buffer in new tab :read [filename] # Will insert the contents of [filename] at the current cursor position /joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
:ju(mps) : list your movements {{help|jump-motions}} \
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.:%s/~/sue/igc substitute your last replacement string with 'sue'.
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
:wa # 'Will save all buffers.
:xa # Will save all buffers and exit Vim.* # g* g# each searches for the word under the cursor (forwards/backwards):%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.)
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern.:vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) < CTRL-n >< CTRL-p > offers word-completion while in insert mode.
:%s//joe/igc substitute your last search with joe.
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) :set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
:tab sball # Will re-tab all files in the buffers list. To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
:Sex # Will open a file explorer in a split window. I bet you'll remember that one. /< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search. You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers. After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
/.*fred&.*joe/ # Will search for fred AND joe, in any order. % matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines. :%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) [I (that is bracket-open, capital-i) shows lines containing the word under the cursor
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
/joe/+3 # Will search for joe and place the cursor three lines below the match. :%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. "+y # to copy to the X11 (or Windows) clipboard.
"+p # to paste from it. http://is.gd/9dkI"2p # Will put the second to last thing yanked
"3p # Will put the third to last, etc. http://is.gd/do1Dt/fred|joe/ # Will search for either fred OR joe. /\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80. http://is.gd/8ekTg; # Will cycle through your recent changes (or g, to go in reverse. In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree." :s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':' :history lists the history of your recent commands, sans duplicates.
gf # Will open the file under the cursor. (Killer feature.) :set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
:lcd %:p:h # Will change to the directory of the current file. g< CTRL-G > # to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYjEdit and encrypt a file: vim -x filename (via @dlibanori)
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"In visual mode, use s" to surround the selected text with " using the surround plugin. http://is.gd/fpwJQ
@: # to repeat the last executed command. http://is.gd/9cuP/begin\_.*end # Will search for begin AND end over multiple lines. %s/^ \ n/ / to delete all empty lines (remove spaces from command!)
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). ga # Will display the ASCII, hex, and octal value of the character under the cursor. :scriptnames # Will list all plugins and _vimrcs loaded. :vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
:g/search_term/# display each line containing 'search_term' with line numbers.
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one). CTRL-w K # Will switch vertical split into horizontalCTRL-w H # Will switch a horizontal into a vertical. :%s/~/sue/igc substitute your last replacement string with sue.
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) ggVG= # Will auto-format the entire document:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph. ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. :tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.:E to see a simple file explorer. (:Ex will too, if thats easier to remember.)
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. :w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) < CTRL-x >< CTRL-l > offers line completion in insert mode.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. '0 opens the last modified file ('1'2 '3 works too)
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence) :vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
2f/ would find the second occurrence of '/' in a line.
Count the number of occurences of a word in a file with :%s/<word>//gn
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance. http://is.gd/XKGK1X
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
/fred|joe/ # Will search for either fred OR joe. CTRL-w K # Will switch vertical split into horizontalCTRL-w H # Will switch a horizontal into a vertical. /< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search. :g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence) :E to see a simple file explorer. (:Ex will too, if thats easier to remember.)
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree." ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). %s/^ \ n/ / to delete all empty lines (remove spaces from command!)
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
/joe/e # Will search for joe and place the cursor at the end of the match. CTRL-w s CTRL-w T # Will open current buffer in new tab :%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. 2f/ would find the second occurrence of '/' in a line.
< CTRL-x >< CTRL-l > offers line completion in insert mode.
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).:wa # Will save all buffers. :xa # Will save all buffers and exit Vim. http://is.gd/do1qZIn insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
"2p # Will put the second to last thing yanked
"3p # Will put the third to last, etc. http://is.gd/do1DtCount the number of occurences of a word in a file with :%s/<word>//gn
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) If you have got a tip for vim users, please submit it at http://bit.ly/eQNaQ9 !
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) :vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA@mxey Patience is a virtue. You can see more at http://vimtweets.com. You can also suggest a tip.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. ggVG= # Will auto-format the entire documentEdit and encrypt a file: vim -x filename (via @dlibanori)
[I (thats bracket-open, capital-i) shows lines containing the word under the cursor
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
ga # Will display the ASCII, hex, and octal value of the character under the cursor. :vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA< CTRL-o > : trace your movements backwards in a file. < CTRL-i > trace your movements forwards in a file.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. :vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) :40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers. K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
'0 opens the last modified file ('1'2 '3 works too)
:Sex # Will open a file explorer in a split window. I bet you'll remember that one. After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin' http://is.gd/fpwJQ
< CTRL-n >< CTRL-p > # offers word-completion while in insert mode. ci " inside a "" # "Will erase everything between "" and place you in insertion mode.
* # g* g# each searches for the word under the cursor (forwards/backwards) g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one). :%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) :ju(mps) : list your movements {{help|jump-motions}} \
/.*fred&.*joe/ # Will search for fred AND joe, in any order. :%s/~/sue/igc substitute your last replacement string with sue.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) :match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
@jon2512chua period repeats the last action, @: repeats the last command-line command. :h @: for more info!
@: to repeat the last executed command. http://is.gd/9cuP
:tab sball # Will re-tab all files in the buffers list. In visual mode, use s" to surround the selected text with " using the surround plugin. http://is.gd/fpwJQ
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
/\%>80v.\+ with search highlighting (:set hlsearch) will highlight any text after column 80. http://is.gd/8ekT
g; # Will cycle through your recent changes (or g, to go in reverse. :%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
:history lists the history of your recent commands, sans duplicates.
:read [filename] # Will insert the contents of [filename] at the current cursor position @vimtips or just set $VISUAL in your shell.
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork":tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo./fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. == # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines. From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. %s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
:lcd %:p:h # Will change to the directory of the current file. :g/search_term/# display each line containing 'search_term' with line numbers.
:scriptnames # Will list all plugins and _vimrcs loaded. :%s//joe/igc substitute your last search with joe.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph. :%s/~/sue/igc substitute your last replacement string with 'sue'.
/joe/+3 # Will search for joe and place the cursor three lines below the match. :e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
/begin\_.*end # Will search for begin AND end over multiple lines. gf # Will open the file under the cursor. (Killer feature.) "+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. :%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) :r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). :s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':' guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.) http://is.gd/tj4y
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using' the surround plugin http://is.gd/fpwJQ
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. < CTRL-x >< CTRL-l > offers line completion in insert mode.
:ju(mps) : list your movements {{help|jump-motions}} \
Many mentioned :Sex opens a file explorer also -- in a split window. Its a different tip! http://is.gd/hInzT Plus, :E is 2 fewer chars
Wow, figured out that d% in #vim # Will delete to the matching brace. Makes sense, but never used it before. /cc @vimtips@: to repeat the last executed command. http://is.gd/9cuP
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.) < CTRL-o > : trace your movements backwards in a file. < CTRL-i > trace your movements forwards in a file.
/fred|joe/ # Will search for either fred OR joe. :%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) /joe/e # Will search for joe and place the cursor at the end of the match. gq{movement} to wrap text, or just gq while in visual mode. gqap will format the current paragraph.
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
:scriptnames # Will list all plugins and _vimrcs loaded. to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"In visual mode, use s" to surround the selected text with " using the surround plugin. http://is.gd/fpwJQ
/.*fred&.*joe/ # Will search for fred AND joe, in any order. ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). * # g* g# each searches for the word under the cursor (forwards/backwards) :vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
Count the number of occurences of a word in a file with :%s/<word>//gn
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one). :%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) :set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) :%s//joe/igc substitute your last search with joe.
:%s/~/sue/igc substitute your last replacement string with sue.
"2p # Will put the second to last thing yanked,
"3p # Will put the third to last, etc. http://is.gd/do1Dt:wa will save all buffers.
:xa # Will save all buffers and exit Vim. http://is.gd/do1qZ:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.:tab sball # Will re-tab all files in the buffers list. Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. == # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines. :vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
'0 opens the last modified file ('1'2 '3 works too)
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) :vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA:read [filename] # Will insert the contents of [filename] at the current cursor position From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
[I (thats bracket-open, capital-i) shows lines containing the word under the cursor
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. :e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) :vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epAggVG= # Will auto-format the entire document/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search. 2f/ would find the second occurrence of '/' in a line.
Anyone interested in a #VIM skin (like http://bit.ly/aYvhSx) for #apple keyboards (w/ or w/o numpad)? Need at least 50 orders! Pls RT and DM:g/search_term/# display each line containing 'search_term' with line numbers.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. ga # Will display the ASCII, hex, and octal value of the character under the cursor. In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.) http://is.gd/tj4y
/joe/+3 # Will search for joe and place the cursor three lines below the match. :%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. :r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
gf # Will open the file under the cursor. (Killer feature.) :h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
g; # Will cycle through your recent changes (or g, to go in reverse. /joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. Gah! Sorry everyone. Those were meant for my personal account, of course.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80. http://is.gd/8ekT:lcd %:p:h # Will change to the directory of the current file. :s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':' "+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
/begin\_.*end # Will search for begin AND end over multiple lines. :40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers. :history lists the history of your recent commands, sans duplicates.
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
[I (thats bracket-open, capital-i) shows lines containing the word under the cursor
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
Actually used C-a and C-x to increment and decrement numbers in some test data. Never thought I had use it!
:wa # Will save all buffers. :xa # Will save all buffers and exit Vim. http://is.gd/do1qZ"2p # Will put the second to last thing yanked,
"3p # Will put the third to last, etc. http://is.gd/do1DtFrom a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
g; # Will cycle through your recent changes (or g, to go in reverse. You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search. :g/search_term/# display each line containing 'search_term' with line numbers.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \vfor more info.) http://is.gd/tj4y
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one). ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epAAfter performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':' :read [filename] # Will insert the contents of [filename] at the current cursor position To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces) :e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s//joe/igc substitute your last search with joe.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'. :%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces) < CTRL-o > : trace your movements backwards in a file. < CTRL-i > trace your movements forwards in a file.
/joe/e # Will search for joe and place the cursor at the end of the match. Technical difficulties with my auto-tweeting. It'll return soon. It may or may not be BP's fault.
Check out these Vim tips from the Thoughtbot crew: http://robots.thoughtbot.com/post/619330025/viiiiiiiiiiiiiiiiiim
You can now search tips at http://vimtweets.com. Check it out, and tell me what you think!
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
:Sex # Will open a file explorer in a split window. I bet you'll remember that one. :E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.) Smash Into Vim! It is the new screencast from PeepCode: http://peepcode.com/products/smash-into-vim-i
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"@panozzaj It should be a command. Sorry. I have updated the tip to read :40,50m30
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). :y<line-number> # Will yank the passed in ln, :y<ln1, ln2> will yank the range.eg. :y41 or :y45,50
#vim/begin\_.*end # Will search for begin AND end over multiple lines. :tab sball # Will re-tab all files in the buffers list. :set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers. :lcd %:p:h # Will change to the directory of the current file. gf # Will open the file under the cursor. (Killer feature.) 2f/ would find the second occurrence of '/' in a line.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces) :r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific). /.*fred&.*joe/ # Will search for fred AND joe, in any order. :h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
ga # Will display the ASCII, hex, and octal value of the character under the cursor. :match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
wrote my first vim plugin! vimsizer, inspired by the great Firesizer for Firefox. http://bit.ly/9eKuOc
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. Bonus tweet for (USA) tax day! Please suggest tweets at vimtweets.com.
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80. http://is.gd/8ekTCtrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
10 Vim Tutorials to Jumpstart Your Editor Skills: http://bit.ly/axRdZY
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. % matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
Announcement: Do you have a vim tip you had like to share? Do you want to browse all vimtips? Check out http://vimtweets.com!
* # g* g# each searches for the word under the cursor (forwards/backwards) @: to repeat the last executed command. http://is.gd/9cuP
< CTRL-x >< CTRL-l > offers line completion in insert mode.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph. g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
:scriptnames # Will list all plugins and _vimrcs loaded. And, of course, follow @vimcasts.
While you are waiting for me to begin steady tweeting again, you should check out http://vimcasts.org!
In case you were worried: tips # Will return soon. I promise."+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA@kevinwatters I don't disagree! It's mostly just cute. "hey look what I can do!":%s/< !--\_.{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces) :h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor. guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
ga # Will display the ASCII, hex, and octal value of the character under the cursor. ggguG # Will lower case the entire file (also known as the Jerry Yang treatment). :%s/~/sue/igc substitute your last replacement string with 'sue'.
:g/search_term/# display each line containing 'search_term' with line numbers.
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.) Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
< CTRL-x >< CTRL-l > offers line completion in insert mode.
gf # Will open the file under the cursor. (Killer feature.) @godfoca . Repeats the last edit. @: repeats the last command-line command. So, :w then @: would write twice. Make sense?
@: to repeat the last executed command. http://is.gd/9cuP
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
:tab sball # Will re-tab all files in the buffers list. Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
@pykler ha! Right, thats what I meant. ;-). Replace def with hours. Sorry.
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).:%s/\v(.*\n){5}/&\r# Will insert a blank line every 5 lines :%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers. :%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy) Tip from 2 days ago should have been %s#.*\ (def\ ).*#\ 1# # Will delete everything on all lines except for the string 'hours'. (no spaces):lcd %:p:h # Will change to the directory of the current file. :%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. :e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search. :vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!/.*fred&.*joe/ # Will search for fred AND joe, in any order. ; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order. /fred|joe/ # Will search for either fred OR joe. Count the number of occurences of a word in a file with :%s/<word>//gn
:history lists the history of your recent commands, sans duplicates.
Added 5 new tips to the db. A sensible way for you to suggest tips is also in the works.
== # Will auto-indent the current line. Select text in visual mode, then == to auto-indent the selected lines. :ju(mps) : list your movements {{help|jump-motions}}
Looking for tips to move text around in vim? http://smartic.us/2010/01/20/moving-text-around-in-vim/
:vmap // y/< C-R >"< CR > # "Will make searching for highlighted text (i.e. in visual mode) require only a highlight and //
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
/joe/+3 # Will search for joe and place the cursor three lines below the match. /fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between. If you're a Ruby developer, check out @ReinH's rubyredgreen plugin for tests from Vim. http://is.gd/6jAut http://screenr.com/gK1
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character. < CTRL-n >< CTRL-p > offers word-completion while in insert mode.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters. I've built up ~70 tips in my db. You'll see tips you've seen previously, if you've been following a while. I know I should add more. :-)
In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
We're back, thanks to a reminder from HN! Tips will be tweeted daily, again. Perhaps I'll rewrite the tip-tweeting app this weekend....
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers. :%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'. * # g* g# each searches for the word under the cursor (forwards/backwards) [Ctrl-d]
# When programming in #vim, you can use Ctrl-d to "De-tab" (Mnemonic) a line and move the cursor back one tab width. #pythonvim -n rather-large-file
# If you need to edit a rather large file. vim swap files can eat up space and be slow. -n will turn them off.:s/-/\n/gc
# Suchen und ersetzen durch Zeilenumbrüche:# Vimrc Tips Add to your Vim configuration:" :w!!
" write the file when you accidentally opened it without the right (root) privileges
cmap w!! w !sudo tee % > /dev/null
:set background=dark
# In vim, depending on whether your terminal background is dark or light, setting this will help with color syntax.# Vim fu# Filetype specific options e.g. no line numbers for markdownau FileType markdown set nonumber
# Copy all:%y+
# Yank all text - Spellcheck:set spell spelllang=en_gb
]s move to the next mispelled word
[s move to the previous mispelled word
zg add a word to the dictionary
zug undo the addition of a word to the dictionary
z= view spelling suggestions for a mispelled word
Visual block mode to add to start or append to end of lines
# Append to the end of all linesvip<C-V>$A,<Esc>
# Explanation: In normal mode, Visual select a paragraph vip, switch to Visual block mode Ctrl-V, append to all lines $A a comma ,.Using I inserts at the start of the line.
# Search and replace globally:%s/x/y/g
# Replaces x with y# Tabs and open files:tabedit {file}
:tabclose
:tabonly
gt switch to next tab
gT switch to previous tab
# Move between open files with:prev
:next
# Changing colour scheme:colorscheme elflord
# changes the colourscheme to elflordSearch
/ is search forward
? is search back
n is find next in the same direction
N is find next in the opposite direction
* find next instance of word under cursor
# find previous instance of word under cursorCtrl-o takes you back
Apend etc
ea is append end of word
ciw change inner word # (i.e. delete word and go into insert mode)Paste into a new line
# Put:nmap <leader>p o<ESC>p
# into your vimrc and use thatUnderling headings in markdown
yypVr-
# From http://vim.wikia.com/wiki/Underline_using_dashes_automaticallyTypewritter scroll mode
# See https://randomdeterminism.wordpress.com/2011/08/15/typewriter-scroll-mode-in-vim/# Unite plugin# http://bling.github.io/blog/2013/06/02/unite-dot-vim-the-plugin-you-didnt-know-you-need/# Removing ^M in text files# http://its.ucsc.edu/unix-timeshare/tutorials/clean-ctrl-m.html# Add in further line-breaks to those that already exist in markdown:%s/ \n/\0\r/g
# Swap two charactersxp
# Turn off highlighting after search:noh
# Interactively replace:%s/old/new/gc
# Removing Ctrl-M# There are quite a few ways of doing this, but a quick way to remove ^M scattered around your file is as follows::%s/C-vC-m//g
# Where C-v is Ctrl-v and C-m is Ctrl-m.# From http://dailyvim.blogspot.co.uk/2009/01/removing-ctrl-m.html:w !sudo tee %
# Ever edit a file as a normal user that is owned by root. This vim command will allow you to overwrite it with root perms.# Sort and remove duplicate lines in a file in one step without intermediary filesvi +'%!sort | uniq' +wq file.txt
# Explanation: We open a file with vi and run two vi commands (specified with +):# %!sort | uniq# % = range definition, it means all the lines in the current buffer.# ! = run filter for the range specified. Filter is an external program, in this example sort | uniq# wq = write buffer contents to file and exit.# Remove offending key from known_hosts file with one swift movevi +18d +wq ~/.ssh/known_hosts
# Explanation: When you try to ssh to a server where the host key has changed then you probably get an error message like this: Offending key in /home/jack/.ssh/known_hosts:18# If you know for sure that it was the server his admins who changed the host key, then your next move is to remove line 18 from the file so that ssh lets you connect after accepting the new key.# The one-liner does this in one swift move by passing simple commands to vi:# +18d -- delete line 18# +wq -- save the file and exit# Sets relative line numbers so that you can easily see how many lines away a line is from the current line.vim tip: set relativenumber
# vim trick: Open a some-file.txt in vim, highlight searchword and jump to first occurrence.vim +/searchword some-file.txt
# Unfortunately the redirection will use UNIX style line endings. If the original files have DOS style line endings, add this command in the subshell:vim +'set ff=dos' +wq converted
vim $( xsel -b | tr "A-Z\ ""a-z_").txt
# Open in vim a file name based on your X paste buffer, but lowercase and underscore spaces.vim scp://user@server1//etc/httpd/httpd.conf
# Edit a file on a remote server using vim from your local *nix desktop# Use vim to pretty-print code with syntax highlightingvim +'hardcopy > output.ps' +q style.css
# Explanation: If you have syntax highlighting properly setup in vim, this command will pretty-print the specified file with syntax highlighting to output.ps. If you prefer PDF, you can convert using ps2pdf output.ps.# vim tip: # Use the % key while cursor over an opening/closing { ( [ or /* to jump to the matching closer or vice versa.display -size 300x300 xc:'#D288AC'# Display a square of the hex value color D288AC. Vim integration: http://bit.ly/1ev2WdI # Replace a regexp pattern in many files at oncevi +'bufdo %s/pattern/replacement/g | update' +q $(grep -rl pattern /path/to/dir)# Explanation: # The inner grep will search recursively in specified directory and print the filenames that contain the pattern.# All files will be opened in vi, one buffer per file.# The arguments starting with + will be executed as vi commands:# bufdo %s/pattern/replacement/g | update = perform the pattern substitution in all files and save the changes# q = exit vi# Limitations: The :bufdo command might not be there in old versions of vim.# Remove carriage return '\r' character in many files, without looping and intermediary filesvi +'bufdo set ff=unix' +'bufdo %s/^M$//' +q file1 file2 file3
# Explanation: The arguments starting with + are commands in vi that will be executed# set ff=unix is a shortcut for set fileformat=unix and means to use "unix" file format, i.e. without the carriage return \r character.# %s/^M$// is a pattern substitution for all lines in the entire buffer, the pattern is "carriage return at end of the line", where ^M is not two literal characters but actually one, to enter it on the command line press Ctrl followed by Enter/Return# bufdo means to run command in all buffers (each file is opened in a separate buffer)# it vi# Note: the set ff=unix is necessary, otherwise the pattern substitution will not do anything if all the lines end with \r = the file is in dos format, because in that case the line ending character will not be considered as part of the line.# Note: if a shell-script has "accidentally" some carriage returns in it, then when you try to execute you may get an error: bad interpreter: No such file or directory. This one-liner fixes that problem. If you know that all the lines in the file have the carriage return, and there is only one file to fix, then a simplified version of the one-liner is enough:vi +'set ff=unix' +wq file1
## Alternative one-liners: # Remove carriage return '\r' character in many files, without looping and intermediary files# Explanation: The recode utility installed on many systems converts between character sets. This command is shorthand for recode IBM-PC..latin1 file1 file2 file3 which converts the given files from CRLF to LF line endings.recode pc..l1 file1 file2 file3
# Remove carriage return '\r' character in many files, without looping and intermediary filesvi +'bufdo set ff=unix' +'bufdo %s/^M$//' +q file1 file2 file3
# Explanation: The arguments starting with + are commands in vi that will be executed# set ff=unix is a shortcut for set fileformat=unix and means to use "unix" file format, i.e. without the carriage return \r character.# %s/^M$// is a pattern substitution for all lines in the entire buffer, the pattern is "carriage return at end of the line", where ^M is not two literal characters but actually one, to enter it on the command line press Ctrl followed by Enter/Return# bufdo means to run command in all buffers (each file is opened in a separate buffer)# q is to quit vi# Note: the set ff=unix is necessary, otherwise the pattern substitution will not do anything if all the lines end with \r = the file is in dos format, because in that case the line ending character will not be considered as part of the line.# Note: if a shell-script has "accidentally" some carriage returns in it, then when you try to execute you may get an error: bad interpreter: No such file or directory. This one-liner fixes that problem. If you know that all the lines in the file have the carriage return, and there is only one file to fix, then a simplified version of the one-liner is enough:vi +'set ff=unix' +wq file1
:%s/[.!?]\_s\+\a/\U&\E/g
#will uppercase the first letter of each sentence (except the very first one). http://is.gd/4xZW:g/_pattern_/s/^/#/g
# will comment out lines containing _pattern_ (if '#' is your comment character/sequence) :vimgrep /stext/ **/*.txt | :copen
# searches for stext recursively in *.txt files and show results in separate window %s/^ \ n/ /
#to delete all empty lines (remove spaces from command!ggVG=
#will auto-format the entire document/\%>80v.\+#with search highlighting (:set hlsearch) will highlight any text after column 80./< CTRL-r >< CTRL-w >
#will pull the word under the cursor into search.:s/\(.*\):\(.*\)/\2 : \1/
#will reverse fields separated by ':' http://is.gd/4xZW/.*fred&.*joe/
#will search for fred AND joe, in any order. http://is.gd/4xZW:e $MYVIMRC#to directly edit your vimrc. :source $MYVIMRC#to reload. Mappings may make it even easier.:%s/^ \ n \{3}//
#will delete a block of 3 empty lines. (remove the spaces) http://is.gd/4xZW:%s/\\/\//g
#Replaces all backslashes with forward slashes.:%s/\ r//g
#to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.ggguG
#will lower case the entire file (also known as the Jerry Yang treatment). http://is.gd/4xZWguu
#converts entire line to lowercase. gUU
#converts entire line to uppercase. ~ inverts case of current character.vim scp://username@host//path/to/file
#to edit a remote file locally. (See http://is.gd/9dwq for dependencies.):%s/\ v(.*\ n){5}/&\ r
# will insert a blank line every 5 lines (remove spaces) http://is.gd/6PB6n:scriptnames
#will list all plugins and _vimrcs loaded. http://is.gd/6PB6n:%s/<word>//gn
#Count the number of occurences of a word in a file with :%s/< ! - -\_.\{-}-- >//
# will delete HTML comments, potentially spanning multiple lines. (remove the spaces) http://is.gd/4xZW%s#<[^>]\+>##g
#will remove HTML tags, leaving the text. (non-greedy) http://is.gd/4xZW:%s//joe/igc
#substitute your last search with joe. http://is.gd/4xZW:w !sudo tee %
#will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?) :%s/^\ n\ +/\ r/
#will compress multiple empty lines into one. (remove spaces) http://is.gd/4xZW:%s/joe|fred/jerks/g
#will replace both 'fred' and 'joe' with 'jerks'. http://is.gd/4xZW:%s#.*(hours).*#1#
#will delete everything on a line except for the string 'hours'. http://is.gd/4xZW:%s/\ v(.*\ n){5}/&\ r
#will insert a blank line every 5 lines (remove spaces) http://is.gd/6PB6n:%s/[.!?]\_s\+\a/\U&\E/g
#will uppercase the first letter of each sentence (except the very first one). http://is.gd/4xZW:s/\(.*\):\(.*\)/\2 : \1/
#will reverse fields separated by ':' http://is.gd/4xZW# Neat @climagic trick: Open a some-file.txt in vim, highlight searchword and jump to first occurrence.vim +/searchword some-file.txt
# Sets relative line numbers so that you can easily see how many lines away a line is from the current line.vim tip: set relativenumber
# Do you have modelines turned on in vim? Check with :verbose set modeline?
# Bulk rename with Vimls | sed 's/^/\"/g;s/$/\"/g' | vim -
:%s/./mv -i & &/g
# Inside the quotes in the second argvi"
:s/\%V /_/g
#" When done - If no slashes at the end of the file name
ggVG
:s/\"\ \"/\/\"\ \"/g
ggVG
:s/\"$/\/\"/g
# Save and quit:w mvs
sh ./mvs
# Inspired by http://vim.wikia.com/wiki/Bulk_rename_files_with_Vim# How can I add a string to the end of each line in Vim?:%s/$/\*/g
# Repace line begining with the string ssh%s/^/ssh /gc
# VI/VIM Anonymize email address in log file - The number 5 means to replace the leading and trailing 5 characters of an "@" in a log file with XXXX@XXXXX.%s/.\{5\}@.\{5\}/XXXXX@XXXXXX/g
# wiederholt letzte kommando - wichtig. in vim wiederholt letzte command
# Nummern am Rand Setzen:set relativenumber
:set norelativenumber
# Suche vim / und ? for search
#==============================##==============================## CMD VIM ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command vim in a clear format. This allows users to quickly access the needed information for vim without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for vim are a valuable resource to work efficiently and purposefully.
Programming languages are formal languages used to write instructions that a computer can execute. They have specific syntax and semantics and are used to develop software, scripts, and applications. Different languages are suited for different tasks, such as web development, system programming, or data analysis. Mastery of multiple programming languages can greatly enhance a developer’s versatility and problem-solving capabilities.
3.1 - 🖥️bash
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the bash command with important options and switches using examples.
# ██████╗ █████╗ ███████╗██╗ ██╗# ██╔══██╗██╔══██╗██╔════╝██║ ██║# ██████╔╝███████║███████╗███████║# ██╔══██╗██╔══██║╚════██║██╔══██║# ██████╔╝██║ ██║███████║██║ ██║# ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝#==============================## CMD BASH#==============================##==============================## To implement a for loop:for file in *;
do echo $file found;
done# To implement a case command:case"$1"in
0) echo "zero found";;
1) echo "one found";;
2) echo "two found";;
3*) echo "something beginning with 3 found";;
esac# Turn on debugging:set -x
# Turn off debugging:set +x
# Retrieve N-th piped command exit statusprintf 'foo' | fgrep 'foo' | sed 's/foo/bar/'echo ${PIPESTATUS[0]}# replace 0 with N# Lock file:( set -o noclobber; echo > my.lock ) || echo 'Failed to create lock file'# Fork bomb:(){ :|:& };:
# Unix Roulette# (Courtesy of Bigown's answer in the joke thread)# DANGER! Don't execute![ $[ $RANDOM % 6 ] == 0 ] && rm -rf /* || echo Click #Roulette# for loop in one linefor i in $(seq 1 4); do echo $i; done# Check to see if a variable equals a specified integerif [ "$var" -eq "0" ]; then echo "var equals zero";
fi# Test if a program exists in the path# There are false positives: aliases and functionscommand -v ${program} >/dev/null 2>&1 || error "${program} not installed"# Redirection# Please note that 2>&1 goes aftermy_command > command-stdout-stderr.txt 2>&1my_command > /dev/null 2>&1# Redirect stdout and stderr of cmd1 to cmd2cmd1 |& cmd2
# Convert spaces to underscores in filenamesfor name in *\ *; do mv -vn "$name""${name// /_}"; done#==============================## CMD BASH#==============================##==============================#[Ctrl-d]
# Last one for today. This indicates to the program that there is no more input. In the shell, this usually closes the shell.[Ctrl-u]
# Delete everything from the cursor to the beginning of the line. This can also be used to clear a password attempt and start over.[Ctrl-w]
# Delete the previous word on the command line (before the cursor). This is highly useful when reusing old commands.[Ctrl-l]
# This is usually equivalent to running 'clear'. Its usually quicker and does not leave the command in your command line history.[Ctrl-_]
# Incremental undo of command line edits.[Meta-#]
# Comment out the current command from the beginning of the line. Faster than [Ctrl-a] then #.[Meta-.]
# Insert the last argument from the previous line in the command history into the current line. This is different from using !$ Press multiple times to keep going back through each history line's last argument.[Ctrl-e]
# Move your cursor to the end of the line. Faster than holding down right arrow.[Ctrl-a]
# Move your cursor to the beginning of the line. Faster than holding down left arrow. In screen, you need to press <Ctrl-a a>[Ctrl-q]
# Sometimes you may find your terminal window appears "frozen". It's not due to the weather. Try pressing Ctrl-q, if that fixes it, its because you hit Ctrl-s. Note: Unfortunately, pressing Ctrl-q multiple times will probably not send you to Hawaii.[Ctrl-r]string
# Reverse search through your command history for 'string'. Press Ctrl-r again to continue searching backwards. ESC when done[C-M]+e
# That's Ctrl + Meta + e. This will expand any history references you make (like !-5$) so you can check before running.(xsel -b || pbpaste) |hexdump -c
# Dump your paste clipboard to hexdump for character by character investigation of what you just copied.# Option Mnemonics: tar xzvf = Xtract Ze Vucking Files [said in thick German accent]# Tip: Sometimes you get yourself into weird situations/trapped signals where Ctrl-C and Ctrl-| do not work. Try Ctrl-z and kill %1.<ctrl-z> bg ; wait %1 ; echo "done" | mail -s "done" you@example.com
# You started a program, but now want it to notify you when its done.longcmd ; [Ctrl-Z] ; bg ; disown ; screen ; reptyr $( pidof longcmd )# Suspend and reattach a process to screen.# Get executed in script its current working directoryCWD=$(cd "$(dirname "$0")" && pwd)# Explanation: Will return excuting script's current working directory, wherever Bash executes the script containing this line.PS1="# $PS1"# Make your prompt safer with # so that if you accidentally copy & paste it, it does not run. Based on @pacohope's idea.# An escaped upper case letter typically means the opposite of its lower case counterpart: \D <-> \d, \S <-> \s, etc.&>
# bash let you use &> to send stdout and stderr to a file. Version 4 or later.$^
# In bash, $^ expands to 2nd word of previous command!?foo
# In bash, !?foo will repeat the most recent command that contained the string 'foo'^foo^bar
# In bash, ^foo^bar repeats the latest command, replacing the first instance of 'foo' with 'bar'!$
# In bash, !$ expands to last word of previous command!:n
# Um das nth Argument der Bash (gezählt von 0) zu erhalten!$
# Um das letzte Argument der Bash zu erhalten bash -c 'swapoff -a && swapon -a'# After killing processing using up all your RAM on Linux (Firefox!!), move processes off of swap.&>
# bash let you use &> to send stdout and stderr to a file. Version 4 or later.(cmd1;cmd2;cmd3)
# When running commands in a subshell, you can use job control (Ctrl-C, Ctrl-Z, fg, bg) on the subshell as a whole unit.:(){ :|:& };:
# DO NOT RUN THIS FORK BOMBHISTCONTROL="ignoreboth"# In bash, this sets the history to ignore commands starting with spaces and duplicates. May already be set.HISTIGNORE="history;ls;date;w;man *"# In bash, this will leave history, ls, date, w and man whatever out of your command history.LANG=C sort
# Setting the LANG=C variable will often fix unexpected problems with sort ignoring symbol characters like +, - and *> file.txt
# This command flush the contents of a file without the need of removing and creating the same file again. This command is very useful in scripting language when we need an output or log on the same file again and again.!#
# Where # should be changed with the actual number of the command. For better understanding, see the below example:!501
# Command of history line 501# Bash Shell Handy Cheatsheet# ^u Clears the line before the cursor position. If you are at the end of the line, clears the entire line.# ^h Same as backspace# ^w Delete (cut) the word before the cursor (to the clipboard)# ^xx Move between start of command line and current cursor position (and back again)# ^t Swap the last two characters before the cursor# ESC-t Swap the last two words before the cursor# Alt/Opt-c Capitalize the character under the cursor and move to the end of the word.# Alt/Opt-l Lower the case of every character from the cursor to the end of the current word.# Alt/Opt-r Cancel the changes and put back the line as it was in the history (revert).# Alt/Opt-t Swap current word with previous# Alt/Opt-u UPPER capitalize every character from the cursor to the end of the current word.# Alt/Opt-Del Delete the Word before the cursor.## !abc:p Print last command starting with abc# !$ (Use) Last argument of previous command# !$:p Print out the word that !$ would substitute# Alt/Opt-. (Get) Last argument of previous command# !* (Use) All arguments of previous command# ^abc^def Run previous command, replacing abc with deftimeout 1 bash -c '</dev/tcp/216.58.207.46/443 && echo Port is open || echo Port is closed' || echo Connection timeout
# How to test a TCP (or UDP) remote port without telnet or netcat (in a one-liner): (google’s IP and TCP to 443) helpful_bash_commands.txt
## BASH ## ctrl-r searches your command history as you type
!!:n # selects the nth argument of the last command, and !$ # the last arg ls file1 file2 file3; cat !!:1-2 # shows all files and cats only 1 and 2 shopt -s cdspell # automatically fixes your 'cd folder' spelling mistakes set editing-mode vi # in your ~/.inputrc to use the vi keybindings for bash and all readline-enabled applications (python, mysql, etc) command < file.in with command <<< "some input text"# Input from the commandline as if it were a file by replacing ^ # is a sed-like operator to replace chars from last command 'ls docs; ^docs^web^' is equal to 'ls web'. The second argument can be empty. nohup ./long_script & # to leave stuff in background even if you logout cd - # change to the previous directory you were working on ctrl-x ctrl-e # opens an editor to work with long or complex command lines## PSEUDO ALIASES FOR COMMONLY USED LONG COMMANDSfunction lt() { ls -ltrsa "$@" | tail; }
function psgrep() { ps axuf | grep -v grep | grep "$@" -i --color=auto; }
function fname() { find . -iname "*$@*"; }
function remove_lines_from() { grep -F -x -v -f $2$1; } # removes lines from $1 if they appear in $2function mcd() { mkdir $1 && cd $1; }
alias pp="ps axuf | pager" alias sum="xargs | tr ' ' '+' | bc"# Usage: echo 1 2 3 | sum## VIM':set spell'# activates vim spellchecker. ']s' and '[s'# to move between mistakes 'zg'# adds to the dictionary 'z='# suggests correctly spelled words# check my .vimrc http://tiny.cc/qxzktw and here http://tiny.cc/kzzktw for more## TOOLS -> htop instead of top
-> ranger is a nice console file manager for vi fans
-> Google 'magic sysrq' to bring a Linux machine back from the dead
-> trash-cli sends files to the trash instead of deleting them forever.
Be very careful with 'rm' or maybe make a wrapper to avoid deleting '*' by accident (e.g. you want to type 'rm tmp*' but type 'rm tmp *')
chmod o+x * -R
# Never run capitalize the X to avoid executable files. find . -type d -exec chmod g+x {} \;# If you want _only_ executable folders: ls *.png | parallel -j4 convert {} {.}.jpg
# run jobs in parallel easily apt-file # to see which package provides that file you are missing dict # is a commandline dictionary sort | uniq # to check for duplicate lines echo start_backup.sh | at midnight # starts a command at the specified time diff --side-by-side fileA.txt fileB.txt | pager # to see a nice diff## NETWORKING# Read on 'ssh-agent' to strenghten your ssh connections using private keys, while avoiding typing passwords every time you ssh.# Use this trick on .ssh/config to directly access 'host2' which is on a private network, and must be accessed by ssh-ing into 'host1' first Host host2 ProxyCommand ssh -T host1 'nc %h %p' HostName host2
tar cz folder/ | ssh server "tar xz"# Pipe a compressed file over ssh to avoid creating large temporary .tgz files or even better, use 'rsync'# ssmtp can use a Gmail account as SMTP and send emails from the command line. echo "Hello, User!" | mail user@domain.com
Configure your /etc/ssmtp/ssmtp.conf:
root=***E-MAIL***
mailhub=smtp.gmail.com:587
rewriteDomain=
hostname=smtp.gmail.com:587
UseSTARTTLS=YES
UseTLS=YES
AuthUser=***E-MAIL***
AuthPass=***PASSWORD***
AuthMethod=LOGIN
FromLineOverride=YES
-~-
If you use 'sshfs_mount' and suffer from disconnects, use '-o reconnect,workaround=truncate:rename' python -m SimpleHTTPServer 8080 or python3 -mhttp.server localhost 8080# shares all the files in the current folder over HTTP. socat TCP4-LISTEN:1234,fork TCP4:192.168.1.1:22 # forwards your port 1234 to another machine's port 22. Very useful for quick NAT redirection.# Some tools to monitor network connections and bandwith: lsof -i monitors network connections in real time
iftop shows bandwith usage per *connection*
nethogs shows the bandwith usage per *process*
ssh -R 12345:localhost:22 server.com "sleep 1000; exit"# forwards server.com's port 12345 to your local ssh port, even if you machine is not externally visible on the net. Now you can ssh localhost -p 12345# from server.com and you will log into your machine. 'sleep' avoids getting kicked out from server.com for inactivity# Silently Execute a Shell Script that runs in the background and won't die on HUP/logout(nohup your-command your-args &>/dev/null &)
# Make your prompt a bit safer with a # prefix so that if you accidentally copy & paste it, at least some lines won't execute.PS1="# $PS1"# Setting the LANG=C variable will often fix unexpected problems with sort ignoring symbol characters like +, - and * or just general weirdness. For instance, I just ran into problems because my LANG was set to en_US.UTF-8.LANG=C sort
[ $(($RANDOM % 2)) -eq 0 ] && command
# Run a command unreliably. In other worse, it will run sometimes. Could be useful in cron, but remember to use \% instead of % if using in crontab.PATH=$PATH:/root
# Put this in your normal user shell profile and freak out the sysadmin. $EDITOR# On hosts with access by others, you may wish to keep the file you are working on out of the process table for privacy or even security reasons. In which case you can start the editor first and then open the file from within.PS1="\t $PS1"# Customized your shell prompt in BASH so that it is prefixed with the current time.stty -echo; grep -F -f- passwords.txt; stty echo
# Use the -f option with - to read search patterns from stdin. Press [Ctrl-d] twice when done. I used -F here for fixed string to avoid things like . matching all. I do all this to avoid passwords in the process table or history.# Escape spaces in stringFILE_PATH=$( echo "$FILE_PATH" | sed 's/ /\\ /g')# Bash command to get current directoryVAR_NAME=$(pwd)# COLORS############################################### Black 0;30 Dark Gray 1;30# Blue 0;34 Light Blue 1;34# Green 0;32 Light Green 1;32# Cyan 0;36 Light Cyan 1;36# Red 0;31 Light Red 1;31# Purple 0;35 Light Purple 1;35# Brown/Orange 0;33 Yellow 1;33# Light Gray 0;37 White 1;37############################################### Set a colorful bash prompt per dev test prod environmentsPS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '# Explanation: It is useful to set a different color for the shell prompt in different deployment environments like dev/test/production, so that you do not mix up your multiple windows and do something by accident in the wrong window.# PS1 contains the format of the primary prompt# \[\e[1;31m\] sets the foreground color to red# \u will be substituted with the current username# \h will be substituted with the hostname# \W will be substituted with the current directory name# \[\e[0m\] is the end marker of the color setting# To make the color stand out even more for root users, the inverse color can be interesting too:# PS1='\[\e[7;31m\][\u@\h \W]\$\[\e[0m\] '# Other color examples:# PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] ' # green# PS1='\[\e[1;33m\][\u@\h \W]\$\[\e[0m\] ' # yellow# PS1='\[\e[1;34m\][\u@\h \W]\$\[\e[0m\] ' # blue# You can learn more in man bash, search for "PROMPTING".# Limitations: Your terminal program must support colors, of course ;-)# A one liner to test, getting the contents of the current working directory:select file in *; dofilename="$file"; done; echo you selected $filename# Tales from malicious scripts.cd /tmp || cd /var/run || cd /mnt || cd /root || cd / || echo "dude your server is really screwed up, I'm outta here." || exit
# Redirect the output of multiple commands{ cmd1 ; cmd2 ; cmd3 ; } > out.out 2> err.out
# Explanation: # Curly braces are very helpful for grouping several commands together# Be careful with the syntax: 1. there must be whitespace after the opening brace 2. there must be a semicolon after the last command and before the closing brace# Another practical use case: test something || { echo message; exit 1; }#==============================##==============================## CMD bash ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command bash in a clear format. This allows users to quickly access the needed information for bash without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for bash are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the cpp command with important options and switches using examples.
# ██████╗██████╗ ██████╗ # ██╔════╝██╔══██╗██╔══██╗# ██║ ██████╔╝██████╔╝# ██║ ██╔═══╝ ██╔═══╝ # ╚██████╗██║ ██║ # ╚═════╝╚═╝ ╚═╝ # C++# # C++ is an object-oriented programming language which provides facilities for low-level memory manipulation.# It is widely used by big tech companies, such as, Amazon, Facebook, Google, and SpaceX## To Compile: g++ my_script.cpp# To Execute: ./a.out## See also # C++ language cheat sheet at /c++/# list of pages: /c++/:list# learn C++: /c++/:learn# C++ one-liners: /c++/:1line# C++ weirdness: /c++/weirdness # search in pages: /c++/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command cpp in a clear format. This allows users to quickly access the needed information for cpp without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for cpp are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the erl command with important options and switches using examples.
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command erl in a clear format. This allows users to quickly access the needed information for erl without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for erl are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the erlang command with important options and switches using examples.
# ███████╗██████╗ ██╗ █████╗ ███╗ ██╗ ██████╗ # ██╔════╝██╔══██╗██║ ██╔══██╗████╗ ██║██╔════╝ # █████╗ ██████╔╝██║ ███████║██╔██╗ ██║██║ ███╗# ██╔══╝ ██╔══██╗██║ ██╔══██║██║╚██╗██║██║ ██║# ███████╗██║ ██║███████╗██║ ██║██║ ╚████║╚██████╔╝# ╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ # Erlang# General-purpose, concurrent, functional programming language, as well as a garbage-collected runtime system.# See also:# erl# Erlang language cheat sheets at /erlang/# list of pages: /erlang/:list# search in pages: /erlang/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command erlang in a clear format. This allows users to quickly access the needed information for erlang without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for erlang are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the gawk command with important options and switches using examples.
# ██████╗ █████╗ ██╗ ██╗██╗ ██╗# ██╔════╝ ██╔══██╗██║ ██║██║ ██╔╝# ██║ ███╗███████║██║ █╗ ██║█████╔╝ # ██║ ██║██╔══██║██║███╗██║██╔═██╗ # ╚██████╔╝██║ ██║╚███╔███╔╝██║ ██╗# ╚═════╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝# Strings bearbeiten mit (g)awk#-----------------------------------------------------------------------///# In Skripten muss ich gelegentlich Ausgaben von Befehlen formatieren oder sonstwie bearbeiten, um sie z.B. als Mailtext eines Cronjobs zu verwenden.uname -n | gawk '{print toupper($0)}'# Das gibt den Hostnamen in Großbuchstaben aus.# Natürlich geht auch das Umwandeln in Kleinbuchstaben:echo ASDFGH | gawk '{print tolower($0)}'# Ergebnis: asdfgh# Vielleicht will ich aber einfach nur wissen, wie lang eine Variable (ein String) ist.echo "dasisteinlangerstring" | gawk '{print length($0)}'# Ergebnis: 21# Gelegentlich bräuchte ich eine hexadezimale Zahl als dezimale.echo 0xAF5D1 | gawk '{print strtonum($0)}'# Ergebnis: 718289# Wichtig bei strtonum ist, dass es Großbuchstaben sein müssen. Das kann ich ja mit toupper zuvor noch machen.# ...Das ist ja recht schön, aber wie kann ich eine Shellvariable an gawk übergeben?String=23halloo1asdfasdf; gawk 'BEGIN {print substr("'"${String}"'",3,5)}'# Ergebnis: hallo# Wenn wir schon bei substring sind, ist der Weg zu split nicht weit:String=vorneundhinten; echo | gawk '{split("'"${String}"'",arr,"und"); print arr[1]}'# Ergebnis: vorne# Das leere "echo" bewirkt das selbe wie "BEGIN" Gawk nimmt es mit Arrays zwar genauer als die Bash, aus irgendwelchen Gründen scheint der Zähler aber bei 1 zu beginnen und nicht bei 0.# Üblicherweise mache ich mit gawk aber viel einfachere Dinge.cat /etc/passwd | gawk -F":"'{print $1,$NF}'# Das zeigt mir alle Linuxuser und ihre Shell, eben das erste und das letzte Feld in der passwd. Der Vorteil von gawk gegenüber cut ist, dass der Feldtrenner aus mehreren Zeichen bestehen kann.# Als simples Beispiel nehme ich mal Folgendes:echo -e "eins und zwei\ndrei und vier\nfuenf und sechs"# Das ergibt:# eins und zwei# drei und vier# fuenf und sechsecho -e "eins und zwei\ndrei und vier\nfuenf und sechs" | gawk -F" und "'{print $1$2}'# Gawk macht dann daraus:# einszwei# dreivier# fuenfsechs# Der Feldtrenner ist in diesem Fall das "und" mit je einem Leerzeichen davor und danach.gawk '{a[$2]++;} ENDFILE {c=0; for (keys in a) { c++;};print c}' 2018*
# Count of total unique column 2 elements seen so far after each file
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command gawk in a clear format. This allows users to quickly access the needed information for gawk without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for gawk are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the gcc command with important options and switches using examples.
# ██████╗ ██████╗ ██████╗# ██╔════╝ ██╔════╝██╔════╝# ██║ ███╗██║ ██║ # ██║ ██║██║ ██║ # ╚██████╔╝╚██████╗╚██████╗# ╚═════╝ ╚═════╝ ╚═════╝# Compile a filegcc file.c
# Compile a file with a custom outputgcc -o file file.c
# Debug symbolsgcc -g
# Debug with all symbols.gcc -ggdb3
# Build for 64 bytesgcc -m64
# Include the directory {/usr/include/myPersonnal/lib/} to the list of path for #include <....># With this option, no warning / error will be reported for the files in {/usr/include/myPersonnal/lib/}gcc -isystem /usr/include/myPersonnal/lib/
# Build a GUI for windows (Mingw) (Will disable the term/console)gcc -mwindows
# Check if a text snippet is valid C codegcc -fsyntax-only -xc - <<< "text snippet"#==============================##==============================## CMD gcc ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command gcc in a clear format. This allows users to quickly access the needed information for gcc without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for gcc are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the gdb command with important options and switches using examples.
# ██████╗ ██████╗ ██████╗ # ██╔════╝ ██╔══██╗██╔══██╗# ██║ ███╗██║ ██║██████╔╝# ██║ ██║██║ ██║██╔══██╗# ╚██████╔╝██████╔╝██████╔╝# ╚═════╝ ╚═════╝ ╚═════╝ # start the debuggergdb your-executable
# set a breakpointb some-method, break some-method
# run the programr, run
# when a breakpoint was reached:# run the current line, stepping over any invocationsn, next
# run the current line, stepping into any invocationss, step
# print a stacktracebt, backtrace
# evaluate an expression and print the resultp length=strlen(string)
# list surrounding source codel, list
# continue executionc, continue# exit gdb (after program terminated)q, quit
#==============================##==============================## CMD GDB ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command gdb in a clear format. This allows users to quickly access the needed information for gdb without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for gdb are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the go command with important options and switches using examples.
# ██████╗ ██████╗ # ██╔════╝ ██╔═══██╗# ██║ ███╗██║ ██║# ██║ ██║██║ ██║# ╚██████╔╝╚██████╔╝# ╚═════╝ ╚═════╝ # Go is a free and open source programming language created at Google# and go is a tool for managing go source code.# Download and install a package, specified by its import path:go get package_path
# Compile and run a source file (it has to contain a main package):go run file.go
# Compile the package present in the current directory:go build
# Execute all test cases of the current package (files have to end with _test.go):go test
# Compile and install the current package:go install
# See also:# Go language cheat sheets at /go/# list of pages: /go/:list# learn go: /go/:learn# search in pages: /go/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command go in a clear format. This allows users to quickly access the needed information for go without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for go are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the js command with important options and switches using examples.
# ██╗███████╗# ██║██╔════╝# ██║███████╗# ██ ██║╚════██║# ╚█████╔╝███████║# ╚════╝ ╚══════╝# js## JavaScript often abbreviated as "JS", is a high-level, dynamic, untyped, interpreted run-time language.# It has been standardized in the ECMAScript language specification.## js is a JavaScript shell, part of SpiderMonkey# to install spidermonkey: (in Debian) apt-get install libmozjs-24-bin# Run the shell in interactive modejs
# Run the JavaScript code in the file hello.jsjs hello.js
# Run hello.js then drop into the interactive shelljs -f hello.js -i
# See also:# JavaScript language cheat sheets at /js/# list of pages: /js/:list# learn JavaScript: /js/:learn# JS one-liners: /js/1line# JS weirdness: /js/weirdness# search in pages: /js/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command js in a clear format. This allows users to quickly access the needed information for js without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for js are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the jshint command with important options and switches using examples.
# ██╗███████╗██╗ ██╗██╗███╗ ██╗████████╗# ██║██╔════╝██║ ██║██║████╗ ██║╚══██╔══╝# ██║███████╗███████║██║██╔██╗ ██║ ██║ # ██ ██║╚════██║██╔══██║██║██║╚██╗██║ ██║ # ╚█████╔╝███████║██║ ██║██║██║ ╚████║ ██║ # ╚════╝ ╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ # jshint# # JSHint is a fork of JSLint. The reasons for the fork is basically that # the author disagrees in some points with Douglas Crockford on JavaScript coding style.## If you're looking for a very high standard for yourself or team, JSLint (by Doug Crockford)# If you want to be a bit more flexible,# or have some old pros on your team that don't buy into JSLint's opinions, try JSHint# to install jshintsudo npm install jshint -g
# lint all the JavaScript files in the current directory:find . -name '*.js' -print0 | xargs -0 jshint
# lint all the JavaScript files in a targeted directory:find ./public/javascripts/ -name '*.js' -print0 | xargs -0 jshint
# Parameter-less options passed to jslint are all set to true by default,# if you want to set it false, just specify 'false' after the optionjshint --bitwise false hello.js
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command jshint in a clear format. This allows users to quickly access the needed information for jshint without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for jshint are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the jslint command with important options and switches using examples.
# ██╗███████╗██╗ ██╗███╗ ██╗████████╗# ██║██╔════╝██║ ██║████╗ ██║╚══██╔══╝# ██║███████╗██║ ██║██╔██╗ ██║ ██║ # ██ ██║╚════██║██║ ██║██║╚██╗██║ ██║ # ╚█████╔╝███████║███████╗██║██║ ╚████║ ██║ # ╚════╝ ╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═╝ # jslint# # The JavaScript Code Quality Tool written by Dougls Crockford# to install jslintsudo npm install jslint -g
# lint all the JavaScript files in the current directory:find . -name '*.js' -print0 | xargs -0 jslint
# lint all the JavaScript files in a targeted directory:find ./public/javascripts/ -name '*.js' -print0 | xargs -0 jslint
# Parameter-less options passed to jslint are all set to true by default,# if you want to set it false, just specify 'false' after the optionjslint --bitwise false hello.js
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command jslint in a clear format. This allows users to quickly access the needed information for jslint without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for jslint are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the julia command with important options and switches using examples.
# ██╗██╗ ██╗██╗ ██╗ █████╗ # ██║██║ ██║██║ ██║██╔══██╗# ██║██║ ██║██║ ██║███████║# ██ ██║██║ ██║██║ ██║██╔══██║# ╚█████╔╝╚██████╔╝███████╗██║██║ ██║# ╚════╝ ╚═════╝ ╚══════╝╚═╝╚═╝ ╚═╝# Julia # high-level dynamic programming language designed to address the needs of high-performance numerical analysis# and computational science while also being effective for general-purpose programming# Execute script from the file; pass additional argumentsjulia script.jl arg1 arg2
# Execute command like arguments like scriptjulia -e 'for x in ARGS; println(x); end' foo bar
# See also:# Julia language cheat sheets at /julia/# list of pages: /julia/:list# learn julia: /julia/:learn# search in pages: /julia/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command julia in a clear format. This allows users to quickly access the needed information for julia without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for julia are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the lua command with important options and switches using examples.
# ██╗ ██╗ ██╗ █████╗ # ██║ ██║ ██║██╔══██╗# ██║ ██║ ██║███████║# ██║ ██║ ██║██╔══██║# ███████╗╚██████╔╝██║ ██║# ╚══════╝ ╚═════╝ ╚═╝ ╚═╝# lua# A powerful, light-weight embeddable programming language.# Start an interactive Lua shell:lua
# Execute a Lua script:lua script_name.lua --optional-argument
# Execute a Lua expression:lua -e 'print( "Hello World" )'# All options are handled in order, except -i. For instance, an invocation like# first set a to 1, then print the value of a (1), and finally run the file script.lualua -e'a=1' -e 'print(a)' script.lua
# See also:# Lua language cheat sheets at /lua/# list of pages: /lua/:list# learn lua: /lua/:learn# search in pages: /lua/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command lua in a clear format. This allows users to quickly access the needed information for lua without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for lua are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the luarocks command with important options and switches using examples.
# ██╗ ██╗ ██╗ █████╗ ██████╗ ██████╗ ██████╗██╗ ██╗███████╗# ██║ ██║ ██║██╔══██╗██╔══██╗██╔═══██╗██╔════╝██║ ██╔╝██╔════╝# ██║ ██║ ██║███████║██████╔╝██║ ██║██║ █████╔╝ ███████╗# ██║ ██║ ██║██╔══██║██╔══██╗██║ ██║██║ ██╔═██╗ ╚════██║# ███████╗╚██████╔╝██║ ██║██║ ██║╚██████╔╝╚██████╗██║ ██╗███████║# ╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝# LuaRocks is the package manager for Lua modules# install luarockswget https://luarocks.org/releases/luarocks-2.4.1.tar.gz
tar zxpf luarocks-2.4.1.tar.gz
cd luarocks-2.4.1
./configure; sudo make bootstrap
# install lua packageluarocks install luasocket
# search for lua packageluarocks search luasec
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command luarocks in a clear format. This allows users to quickly access the needed information for luarocks without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for luarocks are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the make command with important options and switches using examples.
# ███╗ ███╗ █████╗ ██╗ ██╗███████╗# ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝# ██╔████╔██║███████║█████╔╝ █████╗ # ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ # ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗# ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝make ; mpg123 hawaii-five-o-theme.mp3
# Play a song at the end of long running command to notify you. #==============================##==============================## CMD MAKE ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command make in a clear format. This allows users to quickly access the needed information for make without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for make are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the perl command with important options and switches using examples.
# ██████╗ ███████╗██████╗ ██╗ # ██╔══██╗██╔════╝██╔══██╗██║ # ██████╔╝█████╗ ██████╔╝██║ # ██╔═══╝ ██╔══╝ ██╔══██╗██║ # ██║ ███████╗██║ ██║███████╗# ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝# The Perl 5 language interpreter.# Parse and execute a Perl script:perl script.pl
# Check syntax errors on a Perl script:perl -c script.pl
# Parse and execute a perl statement:perl -e perl_statement
# Import module before execution of a perl statement:perl -Mmodule -e perl_statement
# Run a Perl script in debug mode, using perldebug:perl -d script.pl
# Loo[p] over all lines of a file, editing them [i]n-place using a find/replace [e]xpression:perl -p -i -e 's/find/replace/g' filename
# Run a find/replace expression on a file, saving the original file with a given extension:perl -p -i'.old' -e 's/find/replace/g' filename
# See also:# Perl language cheat sheets at /perl/# list of pages: /perl/:list# learn perl: /perl/:learn# perl one-liners: /perl/1line# search in pages: /perl/~keyword#==============================## CMD PERL#==============================##==============================#perl -pi.backup -e 's/\r//' foo.txt
#perl -e 'sub a{@_[1-1]-@_[2-1]};\>print a(1-1,2-1)'#perl -e "s/^(\s*S[\s\S]*?)(\/\/\s*.*)$/\n\/\2\n\1" -p a.c>b.c
#perl -wnle "/RE/ and print" filename
# Use Perl to grep for a regex RE# The good: Many functions take regex arguments# The bad: Limited features compared to PCRE# The ugly: \|, \(, \), \{, \}# Summarizing ed(1) movement commands {n} line #n +{n} n lines down
-{n} n lines up
/ search fwd
? search back
'a go to mark 'a
/(Ch|H|Kh)ann?[aeiu]kk?ah?/
# Regular expression for various spellings of Hanukkah perl -MMIME::Base64 -e 'print encode_base64("john\0john\0passwd")';
am9obgBqb2huAHBhc3N3ZA==
#=======================================================================================================# 1. PERL ONE-LINERS#=======================================================================================================grep -in WORD FILE* | perl -ne 'if (/(.*):(\d*):\s*(.*)\s*/) { print $1, " " x (20 - length $1), " ", "0" x (5 - length $2), $2, " $3\n"}'# Display Table of WORD in FILE* - Displays all occurrences of WORD in the FILE*(s), formatting as a table with filename, line number and line text. - Simple example for short filenames. Seems to cause trouble in Windows command lineegrep -in '(Alabama|"AL")' *.asp | perl -ne 'if (/(.*):(\d*):\s*(.*)\s*/) { print $1, " " x (50 - length $1), " ", "0" x (5 - length $2), $2, " $3\n"}'# Display Table of WORD in FILE* - Displays all occurrences of WORD in the FILE*(s), formatting as a table with filename, line number and line text. - More complex example using egrep and assuming longer filenames (note the '50' in the spaces computation) - Also seems to cause trouble in Windows command line.# Text Trimming and Processing#-----------------------------------------------------------------------cat myfile | perl -ne 'if (/^\s*(.*?)\s*$/s) { print "${1}\n" }'# Trim excess blanks from beginning to end of line. A Cygwin creature. - seems less efficient in practiceperl -ne 'if (/^\s*(.*?)\s*$/s) { print "${1}\n" }' < temp.txt
# Trim excess blanks from beginning to end of line. - Don't forget the tr command! Not that we have use right now...# Infinite "music"perl -e 'use bytes; for($t=0;;$t++){ print chr($t*(($t>>13|$t>>8)&30&$t>>4)); }' | play -t raw -b8 -r8k -e un - vol 0.5
# File/Directory one liners#-----------------------------------------------------------------------ls -R
# Recursively list contents of subdirectoriesls -lAF | perl -e 'while (<>) { next if /^dt/; $sum += (split)[4] } print "$sum\n"'# Find the sum of the sizes of the non-directory files in a directoryls | xargs perl -e '@ARGV = grep( -d $_ , @ARGV); print "@ARGV\n"'# Different formats for the subdirectories of just this directoryls | xargs perl -e '@ARGV = grep( -d $_ , @ARGV); while($dir = shift @ARGV) { print "$dir\n" }'# Different formats for the subdirectories of just this directory# Path Parsing One Liners#=======================================================================================================# Can't use EXPR because it only matches at the beginning of a line.if echo $PATH | grep -q "Program" ; then echo "present"; else echo "absent"; fiif echo $PATH | grep -q "\." ; then echo ". present"; else export PATH=".:$PATH"; echo "added . to path"; fiperl -e "print \"$PATH\" =~ /Program/"# not good for testingif [ "$fram" ]; then echo "found a fram"; else echo "no fram here"; fi# See if a variable existsperl -e "print join qq(\n), split /;/, '%CLASSPATH%' "# Use Perl to do the same thing - to print all the variable names on one line - note this can futz up some pathnamesperl -e "foreach (split ';', '%CLASSPATH%') { print; print qq(\n) }"# Use Perl to do the same thing - to print all the variable names on one line - note this can futz up some pathnamesperl -e 'use bytes; for($t=0;;$t++){ print chr($t*(($t>>13|$t>>8)&30&$t>>4)); }' | play -t raw -b8 -r8k -e un - vol 0.5
# Infinite "music"perl -ne 'print if /start_pattern/../stop_pattern/' file.txt
# Display a block of text: multi-line grep with perl# -n reads input, line by line, in a loop sending to $_ Equivalent to while () { mycode } # -e execute the following quoted string (i.e. do the following on the same line as the perl command) the elipses .. operator behaves like a range, remembering the state from line to line.#=======================================================================================================# DOS Fu One Liners#=======================================================================================================for /F %i IN (lines.txt) DO echo %i
# DOS/Windows Equivalents of Common UNIX Commands - Iterate through all the lines in a file, doing somethingprompt $P$C$D$T$F: $_$+$G$S# DOS/Windows Promptperl -e '$n=0;@a=(a..z,A..Z,0..9," ","!");$A=2**6;$H="3300151524624962270817190703002462370017172463";while($n<length $H){$M.=$a[substr($H,$n,2)];$n+=2};$M=~s/X/${A}th/;print "$M\n"'perl -e '$n=0;@TimToady=(a..z,A..Z,0..9," ","!");$A=2**6;$H="3300151524624962270817190703002462370017172463";while($n<length $H){$M.=$TimToady[substr($H,$n,2)];$n+=2};$M=~s/X/${A}th/;print "$M\n"'# Thought of a better way to do this in this medium.# Rename all files in the current directory by capitalizing the first letter of every word in the filenamesls | perl -ne 'chomp; $f=$_; tr/A-Z/a-z/; s/(?<![.'"'"'])\b\w/\u$&/g; print qq{mv "$f" "$_"\n}'# Explanation: # When you pipe something to perl -ne, each input line is substituted into the $_ variable. The chomp, tr///, s/// perl functions in the above command all operate on the $_ variable by default.# The tr/A-Z/a-z/ will convert all letters to lowercase.# The regular expression pattern (?<![.'])\b\w matches any word character that follows a non-word character except a dot or a single quote.# The messy-looking '"'"' in the middle of the regex pattern is not a typo, but necessary for inserting a single quote into the pattern. (The first single quote # closes the single quote that started the perl command, followed by a single quote enclosed within double quotes, followed by another single quote to continue the perl command.) We could have used double quotes to enclose the perl command, but then we would have to escape all the dollar signs which would make everything less readable.# In the replacement string $& is the letter that was matched, and by putting \u in front it will be converted to uppercase.# qq{} in perl works like double quotes, and can make things easier to read, like in this case above when we want to include double quotes within the string to be quoted.# After the conversions we print a correctly escaped mv command. Pipe this to bash to really execute the rename with | sh.# Limitations: The above command will not work for files with double quotes in the name, and possibly other corner cases.# Generate a sequence of numbersperl -e 'print "$_\n" for (1..10);'# Explanation: Print the number with newline character which could be replaced by any char.# Shuffle lines... | perl -MList::Util=shuffle -e 'print shuffle <>;'# Explanation: Sorting lines is easy: everybody knows the sort command. But what if you want to do the other way around? The above perl one-liner does just that:# -MList::Util=shuffle load the shuffle function from the List::Util package# -e '...' execute Perl command# print shuffle <> call List::Util::shuffle for the lines coming from standard input, read by <>## Related one-liners# Shuffle lines... | perl -MList::Util -e 'print List::Util::shuffle <>'# Explanation: Sorting lines is easy: everybody knows the sort command. But what if you want to do the other way around? The above perl one-liner does just that:# -MList::Util load the List::Util module (as if doing use List::Util inside a Perl script)# -e '...' execute Perl command# print List::Util::shuffle <> call List::Util::shuffle for the lines coming from standard input, read by <># Another way would be sort -R if your version supports that (GNU, as opposed to BSD). In BSD systems you can install coreutils and try gsort -R instead. (For eample on OSX, using MacPorts: sudo port install coreutils.)# Group count sort a log fileA=$(FILE=/var/log/myfile.log; cat $FILE | perl -p -e 's/.*,([A-Z]+)[\:\+].*/$1/g' | sort -u | while read LINE; do grep "$LINE"$FILE | wc -l | perl -p -e 's/[^0-9]+//g'; echo -e "\t$LINE"; done;);echo "$A"|sort -nr
# Explanation: # SQL: SELECT COUNT(x), x FROM y GROUP BY x ORDER BY count DESC;# BASH: a temp var for the last sort: $A=$(the file you want: FILE=/var/log/myfile.log# dump the file to a stream: cat $FILE |# cut out the bits you want to count: perl -p -e 's/.*,([A-Z]+)[\:\+].*/$1/g' |# get a unique list: sort -u |# for each line/value in the stream do stuff: while read LINE; do# dump all lines matching the current value to an inner stream: grep "$LINE" $FILE |# count them: wc -l |# clean up the output of wc and drop the value on stdout: perl -p -e 's/[^0-9]+//g';# drop the current value to stdout: echo -e "\t$LINE";# finish per value operations on the outer stream: done;# finish output to the temp var: );# dump the temp var to a pipe: echo "$A" |# sort the list numerically in reverse: sort -nr# Explanation: Knowing the octal, hexadecimal or decimal code of the ASCII character set can be handy at times. In the past, too often I did things like:perl -e 'for my $n (1 .. 255) { print $n, chr($n), $n, "\n"; }'# ... when a simple man ascii would have done the trick...# On a related note, these all print the letter "A":# echo -e '\0101'# printf '\101'# printf '\x41'# perl -e 'print "\x41"'# Calculate an h index from an EndNote exportMAX=$(NUM=1;cat author.xml |perl -p -e 's/(Times Cited)/\n$1/g'|grep "Times Cited" |perl -p -e 's/^Times Cited:([0-9]*).*$/$1/g'|sort -nr | while read LINE; doif [ $LINE -ge $NUM ]; then echo "$NUM"; fi; NUM=$[$NUM+1]; done;); echo "$MAX"|tail -1
# Explanation: EndNote?! I know but sometimes we have windows users as friends# Rename files with numeric paddingperl -e 'for (@ARGV) { $o = $_; s/\d+/sprintf("%04d", $&)/e; print qq{mv "$o" "$_"\n}}'# Explanation: Basically a one-liner perl script. Specify the files to rename as command line parameters, for example:perl -e '.....' file1.jpg file2.jpg
# In this example the files will be renamed to file0001.jpg and file0002.jpg, respectively. The script does not actually rename anything. It only prints the shell commands to execute that would perform the renaming. This way you can check first that the script would do, and if you want to actually do it, then pipe the output to sh like this:perl -e '.....' file1.jpg file2.jpg | sh
# what is happening in the one-liner perl script:# for (@ARGV) { ... } is a loop, where each command line argument is substituted into the auto-variable $_.# $o = $_ :: save the original filename# s/// :: perform pattern matching and replacement on $_# print qq{...} :: print the mv command, with correctly quoted arguments# Limitations: The script does not cover all corner cases. For example it will not work with files that have double-quotes in their names. In any case, it is safe to review the output of the script first before piping it to sh.# Counting the number of commas in CSV formatperl -ne 'print tr/,//, "\n"' < file.csv | sort -u
# Explanation: Sometimes I need to know if a CSV file has the right number of columns, and how many columns there are. The tr/// operator in perl is normally used to convert a set of characters to another set of characters, but when used in a scalar context like in this example, it returns the number of matches of the specified characters, in this case a comma. The perl command above prints the number of commas in every line of the input file. sort -u sorts this and outputs only the unique lines. If all lines in the CSV file have the same number of commas, there should be one line of output. The number of columns in the file is this number + 1.# Limitations: This one-liner does not handle the more general case when the columns may have embedded commas within quotes. For that you would need a more sophisticated method. This simple version can still be very useful in many common cases.Shuffle lines
... | perl -MList::Util -e 'print List::Util::shuffle <>'# Explanation: Sorting lines is easy: everybody knows the sort command. But what if you want to do the other way around? The above perl one-liner does just that:# -MList::Util load the List::Util module (as if doing use List::Util inside a Perl script)# -e '...' execute Perl command# print List::Util::shuffle <> call List::Util::shuffle for the lines coming from standard input, read by <># Another way would be sort -R if your version supports that (GNU, as opposed to BSD). In BSD systems you can install coreutils and try gsort -R instead. (For eample on OSX, using MacPorts: sudo port install coreutils.)# Best method to organize massive word lists# For simple deduplication of arrays you can use an associative array/hash. Simply use the word as the key and give it a value of true. Enumerating the keys then gives you the deduplicated list of words. If you want that list sorted then simply sort it afterwards. Here's a quick Perl example:#!/usr/bin/perluse strict;
use warnings;
my %words;
while (my $line = <STDIN>) {
chomp($line);
$words{lc($line)} = 1;
}
print join("\n", sort keys %words);
#==============================##==============================## CMD PERL#==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command perl in a clear format. This allows users to quickly access the needed information for perl without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for perl are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the python command with important options and switches using examples.
# ██████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ ███╗ ██╗# ██╔══██╗╚██╗ ██╔╝╚══██╔══╝██║ ██║██╔═══██╗████╗ ██║# ██████╔╝ ╚████╔╝ ██║ ███████║██║ ██║██╔██╗ ██║# ██╔═══╝ ╚██╔╝ ██║ ██╔══██║██║ ██║██║╚██╗██║# ██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║# ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝# Desc: Python is a high-level programming language.# and python is a Python interpreter.# Basic example of server with python# Will start a Web Server in the current directory on port 8000# go to http://127.0.0.1:8000# Python v2.7python -m SimpleHTTPServer
# Python 3python -m http.server 8000# SMTP-Server for debugging, messages will be discarded, and printed on stdout.python -m smtpd -n -c DebuggingServer localhost:1025
# Pretty print a jsonpython -mjson.tool
python -m SimpleHTTPServer
# Start a web server on port 8000 that uses CWD. See http://bit.ly/CLIhttpd for other language examples. The command generates a simple web page over HTTP for the directory structure tree and can be accessed at port 8000 in browser till interrupt signal is sent.python -c "for path in '%CLASSPATH%'.split(';'): print path"# Use Python to print all the variable names on one line - note this can futz up some pathnamespython -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"# Convert CSV to JSON - Replace 'csv_file.csv' with your filename.echo "$(python -V 2>&1)" > file
or
python -V 2> file
# Python version to a file# This command sent the Python version to a file. This is intended to be used in scripts. For some reason, simple redirections didn't work with "python -V" This is sample output cat file
Python 2.6.3
# Zen of Python# or just 'import this' in pythonpython -mthis
# See also:# Python language cheat sheets at /python/# list of pages: /python/:list# learn python: /python/:learn# search in pages: /python/~keyword# Get load average in a more parse-able formatpython -c 'import os; print os.getloadavg()[0]'# Explanation: In short, it runs a Python one-line script which imports the 'os' module and uses it to get the load average. It then indexes into a tuple, using the index of zero. The tuple is like this: (one-minute-average, five-minute-average, fifteen-minute-average), so you could substitute 0 for 1 to get the five minute load average, or 2 to get the fifteen minute load average. I find this really useful when writing larger bash one-liners which require this information, as I do not have to parse the output of uptime.# Limitations: Requires Python.# Random 6-digit numberpython -c 'import random; print(random.randint(0,1000000-1))'# Explanation: Stackoverflow has a dozen different ways to generate numbers, all of which fall apart after 3-4 digits. This solution requires Python to be installed, but is simple and direct.# Limitations: Requires Python, it's not a pure-Bash solutionpython -m ensurepip --default-pip && python -m pip install --upgrade pip setuptools wheel
# Bootstrap python-pip & setuptools#==============================##==============================## CMD PYTHON ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command python in a clear format. This allows users to quickly access the needed information for python without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for python are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the python3 command with important options and switches using examples.
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command python3 in a clear format. This allows users to quickly access the needed information for python3 without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for python3 are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the ruby command with important options and switches using examples.
# ██████╗ ██╗ ██╗██████╗ ██╗ ██╗# ██╔══██╗██║ ██║██╔══██╗╚██╗ ██╔╝# ██████╔╝██║ ██║██████╔╝ ╚████╔╝ # ██╔══██╗██║ ██║██╔══██╗ ╚██╔╝ # ██║ ██║╚██████╔╝██████╔╝ ██║ # ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝# Ruby is a dynamic, reflective, object-oriented, general-purpose programming language# ruby is a ruby interpreter# invoke Ruby from the command line to run the script foo.rbruby foo.rb
# pass code as an argumentruby -e 'puts "Hello world"'# The -n switch acts as though the code you pass to Ruby was wrapped in the following:# while gets# # code here# endruby -ne 'puts $_' file.txt
# The -p switch acts similarly to -n, in that it loops over each of the lines in the input# after your code has finished, it always prints the value of $_# Example: replace e with aecho "eats, shoots, and leaves" | ruby -pe '$_.gsub!("e", "a")'# BEGIN block executed before the loopecho "foo\nbar\nbaz" | ruby -ne 'BEGIN { i = 1 }; puts "#{i} #{$_}"; i += 1'
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command ruby in a clear format. This allows users to quickly access the needed information for ruby without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for ruby are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the rust command with important options and switches using examples.
# ██████╗ ██╗ ██╗███████╗████████╗# ██╔══██╗██║ ██║██╔════╝╚══██╔══╝# ██████╔╝██║ ██║███████╗ ██║ # ██╔══██╗██║ ██║╚════██║ ██║ # ██║ ██║╚██████╔╝███████║ ██║ # ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝# Rust is a systems programming language sponsored by Mozilla Research# See also:# rustc# Rust language cheat sheets at /rust/# list of pages: /rust/:list# search in pages: /rust/~keyword
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command rust in a clear format. This allows users to quickly access the needed information for rust without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for rust are a valuable resource to work efficiently and purposefully.
Version control systems track changes to source code and other files over time. They allow multiple developers to collaborate on a project, manage different versions of files, and revert to previous states if needed. Version control is essential for maintaining the integrity and history of a codebase. It also facilitates branching and merging, enabling parallel development and experimentation.
4.1 - 🖥️bzr
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the bzr command with important options and switches using examples.
# ██████╗ ███████╗██████╗ # ██╔══██╗╚══███╔╝██╔══██╗# ██████╔╝ ███╔╝ ██████╔╝# ██╔══██╗ ███╔╝ ██╔══██╗# ██████╔╝███████╗██║ ██║# ╚═════╝ ╚══════╝╚═╝ ╚═╝# Install bazaar fastimport plugincd ~/.bazaar/plugins
bzr branch lp:bzr-fastimport fastimport
# you can do it manually:# pip install # python setup.py build_ext -i# mv ... ~/.bazaar/plugins# probably you will need this patch:# https://launchpadlibrarian.net/174264005/fix-1314771.debdiff# How to migrate from Bazaar to git:git init
bzr fast-export --plain . | git fast-import
# Mirror from one Subversion repository to another Subversion repositorybzr co https://repo1/proj1/trunk proj1 && cd proj1 && bzr push https://repo2/vendor/proj1/trunk
# Explanation: # The commit history in repo1 will be copied to repo2.# The temporary Bazaar repository (proj1) will have the full history of changes.# The command above initializes the mirror. To update the mirror, run this script, you can schedule it to run periodically to keep the mirror up to date: cd proj1 && bzr up && bzr push# Limitations: # The author information will get lost in the process.
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command bzr in a clear format. This allows users to quickly access the needed information for bzr without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for bzr are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the git command with important options and switches using examples.
# ██████╗ ██╗████████╗# ██╔════╝ ██║╚══██╔══╝# ██║ ███╗██║ ██║ # ██║ ██║██║ ██║ # ╚██████╔╝██║ ██║ # ╚═════╝ ╚═╝ ╚═╝ add, commit, push, and pull.
# Bare minimum git for personal usegit diff --name-only HEAD | cpio -o -Hnewc --quiet | ssh HOST '(cd REPO_DIR && cpio -iduv --quiet -Hnewc)'# Copy uncommitted changes to remote git repository Copy changed files from the remote git repository, _including binary ones_, staged and unstaged alike. Note that this command doesn't handle deleted files properly. The reverse of the excellent commandgitdir="/var/git";find $gitdir -name ".git" 2> /dev/null | sed 's/\/.git/\//g' | awk '{print "\033[1;32m\nRepo ----> \033[0m " $1; system("git --git-dir="$1".git --work-tree="$1" status")}'# List status of your git repos and let us know if there is any new files to commit. Source: http://www.bashoneliners.com/oneliners/oneliner/225/ This is sample output Repo ----> /var/git/router/TG799VAC-XTREME-17.2-MINT/
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: README.md
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: test.sh
# To set your identity:git config --global user.name "John Doe"git config --global user.email johndoe@example.com
# To set your editor:git config --global core.editor emacs
# To enable color:git config --global color.ui true
# To stage all changes for commit:git add --all
# To stash changes locally, this will keep the changes in a separate changelist# called stash and the working directory is cleaned. You can apply changes# from the stash anytimegit stash
# To stash changes with a messagegit stash save "message"# To list all the stashed changesgit stash list
# To apply the most recent change and remove the stash from the stash listgit stash pop
# To apply any stash from the list of stashes. This does not remove the stash# from the stash listgit stash apply stash@{6}
# To commit staged changesgit commit -m "Your commit message"# To edit previous commit messagegit commit --amend
# Git commit in the pastgit commit --date="`date --date='2 day ago'`"git commit --date="Jun 13 18:30:25 IST 2015"# more recent versions of Git also support --date="2 days ago" directly# To change the date of an existing commitgit filter-branch --env-filter \
'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
then
export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
fi'# To removed staged and working directory changesgit reset --hard
# To go 2 commits backgit reset --hard HEAD~2
# To remove untracked filesgit clean -f -d
# To remove untracked and ignored filesgit clean -f -d -x
# To push to the tracked master branch:git push origin master
# To push to a specified repository:git push git@github.com:username/project.git
# To delete the branch "branch_name"git branch -D branch_name
# To make an exisiting branch track a remote branchgit branch -u upstream/foo
# To see who commited which line in a filegit blame filename
# To sync a fork with the master repo:git remote add upstream git@github.com:name/repo.git # Set a new repogit remote -v # Confirm new remote repogit fetch upstream # Get branchesgit branch -va # List local - remote branchesgit checkout master # Checkout local master branchgit checkout -b new_branch # Create and checkout a new branchgit merge upstream/master # Merge remote into local repogit show 83fb499 # Show what a commit did.git show 83fb499:path/fo/file.ext # Shows the file as it appeared at 83fb499.git diff branch_1 branch_2 # Check difference between branchesgit log # Show all the commitsgit status # Show the changes from last commit# Commit history of a set of filesgit log --pretty=email --patch-with-stat --reverse --full-index -- Admin\*.py > Sripts.patch
# Import commits from another repogit --git-dir=../some_other_repo/.git format-patch -k -1 --stdout <commit SHA> | git am -3 -k
# View commits that will be pushedgit log @{u}..
# View changes that are new on a feature branchgit log -p feature --not master
git diff master...feature
# Interactive rebase for the last 7 commitsgit rebase -i @~7
# Diff files WITHOUT considering them a part of git# This can be used to diff files that are not in a git repo!git diff --no-index path/to/file/A path/to/file/B
# To pull changes while overwriting any local commitsgit fetch --all
git reset --hard origin/master
# Update all your submodulesgit submodule update --init --recursive
# Perform a shallow clone to only get latest commits# (helps save data when cloning large repos)git clone --depth 1 <remote-url>
# To unshallow a clonegit pull --unshallow
# Create a bare branch (one that has no commits on it)git checkout --orphan branch_name
# Checkout a new branch from a different starting pointgit checkout -b master upstream/master
# Remove all stale branches (ones that have been deleted on remote)# So if you have a lot of useless branches, delete them on Github and then run thisgit remote prune origin
# The following can be used to prune all remotes at oncegit remote prune $(git remote | tr '\n'' ')# Revisions can also be identified with :/text# So, this will show the first commit that has "cool" in their message bodygit show :/cool
# Undo parts of last commit in a specific filegit checkout -p HEAD^ -- /path/to/file
# Revert a commit and keep the history of the reverted change as a separate revert commitgit revert <commit SHA>
# Pich a commit from a branch to current branch. This is different than merge as# this just applies a single commit from a branch to current branchgit cherry-pick <commit SHA1>
# Undo last commit# If you want to nuke commit C and never see it again# (F)# A-B-C# ↑# mastergit reset --hard HEAD~1
# Undo last commit# If you want to undo the commit but keep your changes# (F)# A-B-C# ↑# mastergit reset HEAD~1
# list files changed in ${commit_id}git diff-tree --no-commit-id --name-only -r ${commit_id}# list files changed in ${commit_id}, porcelain way, meant to be user facinggit show --pretty="" --name-only bd61ad98
# See everything you have done, across branches, in a glance,# then go to the place right before you broke everythinggit reflog
git reset HEAD@{hash}
# To move your most recent commit from one branch and stage it on TARGET branchgit reset HEAD~ --soft
git stash
git checkout TARGET
git stash pop
git add .
#==============================## CMD GIT Versionsverwaltung#==============================##==============================#git log --author=$USER --format="- %B" --since=-7days --reverse |mail -s "What I've done this week" boss@company\.com
git log --date=short --format="%ci"|awk '{print $1}'|uniq
# Which days I've worked... git log --merges | grep ^Date | awk '{ print $2 }' | sort | uniq -c | sort -n
# Number of git merges by day of the week. git config --global core.editor "gvim --nofork"# to use gvim to edit your git messages set gits core editor as followsgit -s
# For more succinct output from git status, add the -s option.git commit -a -m 'commit message'# Using git, add and commit all modified files in one commandgit ls-tree -r --name-only HEAD | tr A-Z a-z | sort | uniq -d
# List files that confuse Git on Windows by differing only by case git push --set-upstream origin master
# Pushing changes to an empty git repository for the first time After cloning an empty repository on the client ("git clone" just after "git init", for instance), "git push" fails. In order to be able to push to this repository for the first time, you need to run the above command. It will link your local "master" branch to the "master" branch in the origin server, and push the changes. This is only necessary only for the first push; after that, you can use just the commands "git push" or "git pull" in order to do this operations.(find . -name \*.git 2>/dev/null|grep -oP '^(.*)(?=\/\.git$)'|while read l;do pushd "$l";git status;popd;printf "\n";done)
# find git# Repostitory anlegen# -------------------cd /home/git
mkdir <Zielverzeichnis>
cp -r <Quelle> <Zielverzeichnis>
cd <Zielverzeichnis>
git init
git config --global user.name "Tux Git"git config --global user.email "tux.git@lxu.io"# alle Dateien im aktuellen Verzeichnis und Unterverzeichnis hinzufügengit add .
git commit -am "Postfix Konfiguration MX4"# Repository anschauen# --------------------git status
# zeigt commits an (--oneline optional)git log --oneline
# zeigt auch alte commits angit reflog
# diffs anschauengit show -1
# diff zwischen jetzt und zwei Commits zurückgit diff HEAD~2 HEAD main.cf
# Aenderung committen# -------------------cd /home/git/<Zielverzeichnis>
cp <Quelldatei> <Zielverzeichnis>
# geaenderten Status anzeigengit status
git commit -am "Update main.cf"# Log anschauengit log --oneline
# alte Version auschecken# ------------------------git checkout <gehashte Version>
# Dateien liegen jetzt im alter Version vor ->git status# optional wieder auf alten Head zurückgehen mit# git reflog# git reset --hard <gehashte Version># git status zeigt jetzt "HEAD losgelöst"# git checkout master# git status -> steht auf mastergit show $COMMIT# ORgit diff HEAD^ HEAD
# Diff Against the Previous Commitsgit diff --ignore-space-change myFile.txt
# How to git diff a file version excluding space differences - This git command allows to get differences on local modified file ignoring space or blanks as changesgit init
git remote add origin PATH/TO/REPO
git fetch
git reset --hard origin/master
# Git Clone into non empty directoryUsing Git===============
Global Settings
-----------
Related Setup: https://gist.github.com/hofmannsven/6814278
Related Pro Tips: https://ochronus.com/git-tips-from-the-trenches/
Interactive Beginners Tutorial: http://try.github.io/
Reminder
-----------
Press `minus + shift + s` and `return` to chop/fold long lines!
Show folder content: `ls -la`Notes
-----------
Do not put (external) dependencies in version control!
Setup
-----------
See where Git is located:
`which git`Get the version of Git:
`git --version`Create an alias (shortcut) for`git status`:
`git config --global alias.st status`Help
-----------
Help:
`git help`General
-----------
Initialize Git:
`git init`Get everything ready to commit:
`git add .`Get custom file ready to commit:
`git add index.html`Commit changes:
`git commit -m "Message"`Add and commit in one step:
`git commit -am "Message"`Remove files from Git:
`git rm index.html`Update all changes:
`git add -u`Remove file but do not track anymore:
`git rm --cached index.html`Move or rename files:
`git mv index.html dir/index_new.html`Undo modifications (restore files from latest commited version):
`git checkout -- index.html`Restore file from a custom commit (in current branch):
`git checkout 6eb715d -- index.html`Reset
-----------
Go back to commit:
`git revert 073791e7dd71b90daa853b2c5acc2c925f02dbc6`Soft reset (move HEAD only; neither staging nor working dir is changed):
`git reset --soft 073791e7dd71b90daa853b2c5acc2c925f02dbc6`Undo latest commit: `git reset --soft HEAD~ `Mixed reset (move HEAD and change staging to match repo; does not affect working dir):
`git reset --mixed 073791e7dd71b90daa853b2c5acc2c925f02dbc6`Hard reset (move HEAD and change staging dir and working dir to match repo):
`git reset --hard 073791e7dd71b90daa853b2c5acc2c925f02dbc6`Update & Delete
-----------
Test-Delete untracked files:
`git clean -n`Delete untracked files (not staging):
`git clean -f`Unstage (undo adds):
`git reset HEAD index.html`Commit to most recent commit:
`git commit --amend -m "Message"`Update most recent commit message:
`git commit --amend -m "New Message"`Branch
-----------
Show branches:
`git branch`Create branch:
`git branch branchname`Change to branch:
`git checkout branchname`Create and change to new branch:
`git checkout -b branchname`Rename branch:
`git branch -m branchname new_branchname` or:
`git branch --move branchname new_branchname`Show all completely merged branches with current branch:
`git branch --merged`Delete merged branch (only possible if not HEAD):
`git branch -d branchname` or:
`git branch --delete branchname`Delete not merged branch:
`git branch -D branch_to_delete`Merge
-----------
True merge (fast forward):
`git merge branchname`Merge to master (only if fast forward):
`git merge --ff-only branchname`Merge to master (force a new commit):
`git merge --no-ff branchname`Stop merge (in case of conflicts):
`git merge --abort`Stop merge (in case of conflicts):
`git reset --merge` // prior to v1.7.4
Merge only one specific commit:
`git cherry-pick 073791e7`Stash
-----------
Put in stash:
`git stash save "Message"`Show stash:
`git stash list`Show stash stats:
`git stash show stash@{0}`Show stash changes:
`git stash show -p stash@{0}`Use custom stash item and drop it:
`git stash pop stash@{0}`Use custom stash item and do not drop it:
`git stash apply stash@{0}`Delete custom stash item:
`git stash drop stash@{0}`Delete complete stash:
`git stash clear`Gitignore & Gitkeep
-----------
About: https://help.github.com/articles/ignoring-files
Useful templates: https://github.com/github/gitignore
Add or edit gitignore:
`nano .gitignore`Track empty dir:
`touch dir/.gitkeep`Log
-----------
Show commits:
`git log`Show oneline-summary of commits:
`git log --oneline`Show oneline-summary of commits with full SHA-1:
`git log --format=oneline`Show oneline-summary of the last three commits:
`git log --oneline -3`Show only custom commits:
`git log --author="Sven"``git log --grep="Message"``git log --until=2013-01-01``git log --since=2013-01-01`Show only custom data of commit:
`git log --format=short``git log --format=full``git log --format=fuller``git log --format=email``git log --format=raw`Show changes:
`git log -p`Show every commit since special commit for custom file only:
`git log 6eb715d.. index.html`Show changes of every commit since special commit for custom file only:
`git log -p 6eb715d.. index.html`Show stats and summary of commits:
`git log --stat --summary`Show history of commits as graph:
`git log --graph`Show history of commits as graph-summary:
`git log --oneline --graph --all --decorate`Compare
-----------
Compare modified files:
`git diff`Compare modified files and highlight changes only:
`git diff --color-words index.html`Compare modified files within the staging area:
`git diff --staged`Compare branches:
`git diff master..branchname`Compare branches like above:
`git diff --color-words master..branchname^`Compare commits:
`git diff 6eb715d``git diff 6eb715d..HEAD``git diff 6eb715d..537a09f`Compare commits of file:
`git diff 6eb715d index.html``git diff 6eb715d..537a09f index.html`Compare without caring about spaces:
`git diff -b 6eb715d..HEAD` or:
`git diff --ignore-space-change 6eb715d..HEAD`Compare without caring about all spaces:
`git diff -w 6eb715d..HEAD` or:
`git diff --ignore-all-space 6eb715d..HEAD`Useful comparings:
`git diff --stat --summary 6eb715d..HEAD`Blame:
`git blame -L10,+1 index.html`Releases & Version Tags
-----------
Show all released versions:
`git tag`Show all released versions with comments:
`git tag -l -n1`Create release version:
`git tag v1.0.0`Create release version with comment:
`git tag -a v1.0.0 -m 'Message'`Checkout a specific release version:
`git checkout v1.0.0`Collaborate
-----------
Show remote:
`git remote`Show remote details:
`git remote -v`Add remote origin from GitHub project:
`git remote add origin https://github.com/user/project.git`Add remote origin from existing empty project on server:
`git remote add origin ssh://root@123.123.123.123/path/to/repository/.git`Remove origin:
`git remote rm origin`Show remote branches:
`git branch -r`Show all branches:
`git branch -a`Compare:
`git diff origin/master..master`Push (set default with `-u`):
`git push -u origin master`Push to default:
`git push origin master`Fetch:
`git fetch origin`Fetch a custom branch:
`git fetch origin branchname:local_branchname`Pull:
`git pull`Pull specific branch:
`git pull origin branchname`Merge fetched commits:
`git merge origin/master`Clone to localhost:
`git clone https://github.com/user/project.git` or:
`git clone ssh://user@domain.com/~/dir/.git`Clone to localhost folder:
`git clone https://github.com/user/project.git ~/dir/folder`Clone specific branch to localhost:
`git clone -b branchname https://github.com/user/project.git`Delete remote branch (push nothing):
`git push origin :branchname` or:
`git push origin --delete branchname`Archive
-----------
Create a zip-archive: `git archive --format zip --output filename.zip master`Export/write custom log to a file: `git log --author=sven --all > log.txt`Troubleshooting
-----------
Ignore files that have already been committed to a Git repository: http://stackoverflow.com/a/1139797/1815847
Security
-----------
Hide Git on the web via `.htaccess`: `RedirectMatch 404 /\.git`(more info here: http://stackoverflow.com/a/17916515/1815847)
Large File Storage
-----------
Website: https://git-lfs.github.com/
Install: `brew install git-lfs`Track `*.psd` files: `git lfs track "*.psd"` (init, add, commit and push as written above)
# Delete first 10 branches from remote origin (exclude master)git branch -a | grep "remotes/origin" | grep -v master | sed 's/^[ *]*//' | sed 's/remotes\/origin\///' | head -n10 | sed 's/^/git push origin :/' | bash
# Clone all repos from a user with lynx# https://wuseman.github.io/wcloner/lynx -dump -nonumbers https://github.com/USER?tab=repositories|grep '/USER/'|cut -d'/' -f1,2,3,4,5|uniq|xargs -L1 git clone
# Holt mir das remote Verzeichnis git clone git@linux.lxu.io:/home/git/linux_lxu_io
#-----------------------------------------------------------------------///# git-usage-stats626 status
544 commit
526 add
411 lg
253 diff
249 grep
224 checkout
207 rebase
164 push
163 show
132 stash
97 log
76 rebaselocal
58 reset
51 pull
49 b
42 mergetool
29 branch
27 stauts
27 clean
23 hgrep
20 lga
18 pull-request
18 cherry-pick
14 open
12 tag
12 rm
11 merge
11 blame
10 chkdelete
9 mv
8 whitespacecheckout
8 remote
8 lgaa
8 dif
8 browse
7 lgu
7 fetch
5 lgb
5 clone
4 l
43 lgd
3 lgaaa
3 g
3 diffchar
2 update
2 satus
2 revert
2 pul
2 lug
2 ls-files
2 list
2 --help
2 help
2 diffword
2 difff
1 vomm
1 staut
1 shiw
1 review
1 psh
1 phpsh
1 phps
1 mertet-y
1 ls
1 lgaaaa
1 lb
1 devel
1 dd
1 create
1 commm-a
1 commm
1 com
1 chek-p
1 chekout
1 chekc-p
1 chek-
1 adiff
1 ad
#-----------------------------------------------------------------------///git log --author=$USER --format="- %B" --since=-7days --reverse |mail -s "What I've done this week" boss@company\.com
# Mail a report of what you've done this week to your boss.# Export a git project to a directorygit archive master | tar x -C /path/to/dir/to/export
# Explanation: The git archive command basically creates a tar file. The one-liner is to create a directory instead, without an intermediate tar file. The tar command above will untar the output of git archive into the directory specified with the -C flag. The directory must exist before you run this command.# List all non Git comited files and make a gzip archive with themGITFOLDER="/srv/some/folder" ls-files --others --exclude-standard | tar czf ${GITFOLDER}-archives/uploads-$(date '+%Y%m%d%H%M').tar.gz -T -
# Explanation: Assuming your web app has a git checkout is in /srv/some/folder (i.e. there is a /srv/some/folder/.git), archive the user uploads to /srv/some/folder-archives with that one liner. Use:cd /srv/some/folder
# this one-liner# Limitations: A fully complete script would:# Check if $GITFOLDER exists# Check if $GITFOLDER has a .git directory# Create a temporary (e.g. tmp=$(mktemp)) file to log anything; if [ "$?" -ne 0 ] ; exit with status exit 1, otherwise delete the $tmp file and exit 0.# Count the lines of each file extension in a list of filesgit ls-files | xargs wc -l | awk -F ' +|\\.|/''{ sumlines[$NF] += $2 } END { for (ext in sumlines) print ext, sumlines[ext] }'# Explanation: The pipeline:# git ls-files -- produces the list of files in a Git repository. It could be anything else that produces a list of filenames, for example: find . -type f# xargs wc -l -- run wc -l to count the lines in the filenames coming from standard input. The output is the line count and the filename# The final awk command does the main work: extract the extension name and sum the line counts:# -F ' +|\\.|/' -- use as field separator multiples of spaces, or a dot, or a slash# { sumlines[$NF] += $2 } -- $NF contains the value of the last field, which is the filename extension, thanks to the dot in the field separator, and $2 contains the value of the second field in the input, which is the line count. As a result, we are building the sumlines associative array, summing up the line counts of files with the same extension# END { for (ext in sumlines) print ext, sumlines[ext] }' -- After all lines have been processed, print the extension and the line count.# Random Git Commitgit commit -m "$(w3m whatthecommit.com | head -n 1)"# Explanation: This will commit a message pulled from What the Commit. -m allows you to provide the commit message without entering your editor w3m is a terminal based web browser. We basically use it to strip out all of the html tags head -n 1 will grab only the first line# Limitations: This requires you to have w3m installed# Test git archive before actually creating an archive // fake dry rungit archive master some/project/subdir | tar t
# Explanation: git archive does not have a --dry-run flag, and it would be nice to see what files would be in the archive before actually creating it.# git archive master some/project/subdir# Create an archive from the master branch, with only a specified sub-directory of the project in it (instead of the entire repo)# Note: without specifying a file, the archive is dumped to standard output# tar t : the t flag of tar is to list the content of an archive. In this example the content comes from standard input (piped from the previous command)# In other words, this command creates an archive without ever saving it in a file, and uses tar t to list the contents. If the output looks good, then you can create the archive with:git archive master -o file.tar some/project/subdir
# Scan entire Git repo for dangerous Amazon Web Service IDsgit grep -Ew '[A-Z0-9]{20}'# Explanation: # Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.# Use Git to quickly search for things that look like AWS IDs: a 20-character uppercase word. The -w adds word boundaries around the search pattern, and the -E make it possible to use extended regex syntax, in this example the {20} count.## Related one-liners# Scan entire Git repos for dangerous Amazon Web Service IDsgit ls-tree --full-tree -r --name-only HEAD | xargs egrep -w '[A-Z0-9]{20}'# Explanation: Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.# Use Git to quickly list all files in the repos. Then, take this list and search for things that look like AWS IDs: a 20-character uppercase word.# Scan entire Git repos for dangerous Amazon Web Service IDsgit ls-tree --full-tree -r --name-only HEAD | xargs egrep -w '[A-Z0-9]{20}'# Explanation: Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.# Use Git to quickly list all files in the repos. Then, take this list and search for things that look like AWS IDs: a 20-character uppercase word.## Alternative one-liners: # Scan entire Git repo for dangerous Amazon Web Service IDsgit grep -Ew '[A-Z0-9]{20}'# Explanation: Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.# Use Git to quickly search for things that look like AWS IDs: a 20-character uppercase word. The -w adds word boundaries around the search pattern, and the -E make it possible to use extended regex syntax, in this example the {20} count.# Print a count of the commits per day in a git repo.git log --pretty=format:%cd --date=short | uniq -c
# Cleanup remote repository of all branches already merged into master This is useful in teams where developers don't bother to remove branches after merging PR. These branches make it hard to seek for really useful branches, which gives us a nice value of finding and exploring other people's code even before they create PR for it.git branch --remotes --merged | grep -v master | sed 's@ origin/@:@' | xargs git push origin
git log -p --name-only --follow <file>
# get full git commit history of single file# rwxr-xr-x$(cd "$(dirname "${BASH_SOURCE[0]}")" && git rev-parse --show-toplevel)# Get the full path of a bash script's Git repository head.# Rather than complicated and fragile paths relative to a script like "../../other", this command will retrieve the full path of the files repository head. Safe with spaces in directory names. Works within a symlinked directory. Broken down: cd "$(dirname "${BASH_SOURCE[0]}")" temporarily changes directories within this expansion. Double quoted "$(dirname" and ")" with unquoted ${BASH_SOURCE[0]} allows spaces in the path. git rev-parse --show-toplevel gets the full path of the repository head of the current working directory, which was temporarily changed by the "cd".# Scan entire Git repo for dangerous Amazon Web Service IDsgit grep -Ew '[A-Z0-9]{20}'# Scan entire Git repos for dangerous Amazon Web Service IDsgit ls-tree --full-tree -r --name-only HEAD | xargs egrep -w '[A-Z0-9]{20}'# Print the list of your Git commits this monthgit log --since='last month' --author="$(git config user.name)" --oneline
git config --add user.name "git User" ; git config --add user.email "gir@localhost" ; git config --add color.ui "auto"# Rename all .markdown files in a git repository .mdfor file in *markdown; do git mv $file`echo $file | cut -f1 -d'.'`.md ; done# Pull multiple repositories in child folders (a.k.a. I'm back from leave script) [Windows]gci -Directory | foreach {Push-Location $_.Name; git fetch --all; git checkout master; git pull; Pop-Location}
# Stage all files for commit except those that are *.config at any level within your git repo [Windows]git status | Where-Object {$_.Contains('modified') -and !$_.Contains('.config')} | ForEach-Object { git add $_.Replace('modified:','').Trim() }
# Copy current branch to clipboard [Windows](git branch | Where-Object { $_.Contains('*') } | Select-Object -First 1).Trim('*').Trim() | Set-Clipboard
# Delete all local branches that are not master [Windows]git branch | Where-Object { !$_.Contains('master') } | ForEach-Object { git branch -D $_.Trim() }
# Delete all local branches that have been merged into master [Windows]git branch --merged origin/master | Where-Object { !$_.Contains('master') } | ForEach-Object { git branch -d $_.trim() }
# Initialise git in working directory with latest Visual Studio .gitignore [Windows]git init; (Invoke-WebRequest https://raw.githubusercontent.com/github/gitignore/master/VisualStudio.gitignore -UseBasicParsing).Content | Out-File -FilePath .gitignore -Encoding utf8; git add -A
# Open browser from terminal to create PR after pushing something in Git in MACgit remote -v |grep origin|tail -1|awk '{print $2}'|cut -d"@" -f2|sed 's/:/\//g'|xargs -I {} open -a "Google Chrome" https://{}
# Delete all local git branches that have been merged and deleted from remotegit branch -d $( git branch -vv | grep '\[[^:]\+: gone\]' | awk '{print $1}' | xargs )# Print all git repos from a user (only curl and grep)curl -s https://api.github.com/users/<username>/repos?per_page=1000 | grep -oP '(?<="git_url": ").*(?="\,)'# Print all git repos from a user - Python is installed on many boxes (in case you could not afford installing jq).curl -s "https://api.github.com/users/<username>/repos?per_page=1000" | python <(echo "import json,sys;v=json.load(sys.stdin);for i in v:; print(i['git_url']);" | tr ';''\n')
# Print all git repos from a user - in case you could afford installing jqcurl -s "https://api.github.com/users/<username>/repos?per_page=1000" | jq '.[].git_url'# Print the list of your Git commits this monthgit log --since='last month' --author="$(git config user.name)" --oneline
# Print github url for the current url - Works for repos cloned via ssh or https.git remote -v | sed -n '/github.com.*push/{s/^[^[:space:]]\+[[:space:]]\+//;s|git@github.com:|https://github.com/|;s/\.git.*//;p}'# Sample output# Cloned using https#----------------------## $ git remote -v# origin https://github.com/bartonski/barton-unit-circle.git (fetch)# origin https://github.com/bartonski/barton-unit-circle.git (push)# $ git remote -v | sed -n '/github.com.*push/{s/^[^[:space:]]\+[[:space:]]\+//;s|git@github.com:|https://github.com/|;s/# \.git.*//;p}'# https://github.com/bartonski/barton-unit-circle#----------------------## cloned using ssh# $ git remote -v# origin git@github.com:bartonski/barton-unit-circle.git (fetch)# origin git@github.com:bartonski/barton-unit-circle.git (push)# Fri Oct 11 12:44:43 bartonc@BartonCW10L: /tmp/barton-unit-circle# $ git remote -v | sed -n '/github.com.*push/{s/^[^[:space:]]\+[[:space:]]\+//;s|git@github.com:|https://github.com/|;s/# \.git.*//;p}'# https://github.com/bartonski/barton-unit-circle# push to Githubgit add -u;
git commit -m "New backup `date +'%Y-%m-%d %H:%M:%S'`";
git push origin master
## Git# remove a repofind . -type f | grep -i ".git" | xargs rm
cd ..
rm -rf
# sets your name and email for commit messagesgit config --global user.name 'John Doe'git config --global user.email johndoe@example.com
# helps recover from mess ups! a log of your last few actionsgit reflog
#!/bin/bash# gitbackup.sh# Create a shell script and name it whatever you want, like backup.sh# How to backup/sync all of your dotfiles with Github# There are many dotfiles in my machine such as .alias, .vimrc, .zshrc, .gitconfig etc...# Initiate an empty Git repository with $ git init and connect the local repo to newly created repowith $ git remote add git@github.com:yourusername/yourrepo.git
# check to see is git command line installed in this machineIS_GIT_AVAILABLE="$(git --version)"if [[ $IS_GIT_AVAILABLE == *"version"* ]]; then echo "Git is Available"else echo "Git is not installed" exit 1fi######### make execudable chmod +x gitbackup.sh.
# Run the script with $ ./gitbackup.sh
# this is open the cronjobs table in vim mode use i for insert modecrontab -e and add your script path and time you want to run the script for example
crontab -e
# this is run the script every minutes*/10 * * * * cd /Users/macp15/Projects/dotfiles/scripts/gitbackup && ./gitbackup.sh
# display list of cron jobscrontab -l
########## Check git status ##gs="$(git status | grep -i "modified")" echo "${gs}"# If there is a new changeif [[ $gs == *"modified"* ]]; then echo "push"fi# The `git show` command may _show_ files from a specific branch or revisiongit show origin/gh-pages:index.html
# Bash tip, capturing standard out & error to a variable..._git_status="$( { git status; } 2>&1)"tee "./index.html" <<<"$(git show gh-pages:index.html)"#==============================##==============================## CMD git ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command git in a clear format. This allows users to quickly access the needed information for git without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for git are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the git-add command with important options and switches using examples.
# ██████╗ ██╗████████╗ █████╗ ██████╗ ██████╗ # ██╔════╝ ██║╚══██╔══╝ ██╔══██╗██╔══██╗██╔══██╗# ██║ ███╗██║ ██║█████╗███████║██║ ██║██║ ██║# ██║ ██║██║ ██║╚════╝██╔══██║██║ ██║██║ ██║# ╚██████╔╝██║ ██║ ██║ ██║██████╔╝██████╔╝# ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═════╝ # git add# Adds changed files to the index.# Add a file to the index: git add path/to/file
# Add all files (tracked and untracked): git add -A
# Only add already tracked files: git add -u
# Also add ignored files: git add -f
# Add parts of a file interactively: git add -p path/to/file
# git add question answers:# y stage this hunk for the next commit# n do not stage this hunk for the next commit# q quit; do not stage this hunk or any of the remaining hunks# a stage this hunk and all later hunks in the file# d do not stage this hunk or any of the later hunks in the file# g select a hunk to go to# / search for a hunk matching the given regex# j leave this hunk undecided, see next undecided hunk# J leave this hunk undecided, see next hunk# k leave this hunk undecided, see previous undecided hunk# K leave this hunk undecided, see previous hunk# s split the current hunk into smaller hunks# e manually edit the current hunk# ? print hunk help
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command git-add in a clear format. This allows users to quickly access the needed information for git-add without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for git-add are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the github command with important options and switches using examples.
# ██████╗ ██╗████████╗██╗ ██╗██╗ ██╗██████╗ # ██╔════╝ ██║╚══██╔══╝██║ ██║██║ ██║██╔══██╗# ██║ ███╗██║ ██║ ███████║██║ ██║██████╔╝# ██║ ██║██║ ██║ ██╔══██║██║ ██║██╔══██╗# ╚██████╔╝██║ ██║ ██║ ██║╚██████╔╝██████╔╝# ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ As a contributor to open-source
-------------------------------
# clone your own project$ git clone dotfiles
→ git clone git://github.com/YOUR_USER/dotfiles.git
# clone another project$ git clone github/hub
→ git clone git://github.com/github/hub.git
# see the current project's issues$ git browse -- issues
→ open https://github.com/github/hub/issues
# open another project's wiki$ git browse mojombo/jekyll wiki
→ open https://github.com/mojombo/jekyll/wiki
## Example workflow for contributing to a project:$ git clone github/hub
$ cd hub
# create a topic branch$ git checkout -b feature
→ ( making changes ... )
$ git commit -m "done with feature"# It's time to fork the repo!$ git fork
→ (forking repo on GitHub...)
→ git remote add YOUR_USER git://github.com/YOUR_USER/hub.git
# push the changes to your new remote$ git push YOUR_USER feature
# open a pull request for the topic branch you've just pushed$ git pull-request
→ (opens a text editor for your pull request message)
As an open-source maintainer
----------------------------
# fetch from multiple trusted forks, even if they don't yet exist as remotes$ git fetch mislav,cehoffman
→ git remote add mislav git://github.com/mislav/hub.git
→ git remote add cehoffman git://github.com/cehoffman/hub.git
→ git fetch --multiple mislav cehoffman
# check out a pull request for review$ git checkout https://github.com/github/hub/pull/134
→ (creates a new branch with the contents of the pull request)
# directly apply all commits from a pull request to the current branch$ git am -3 https://github.com/github/hub/pull/134
# cherry-pick a GitHub URL$ git cherry-pick https://github.com/xoebus/hub/commit/177eeb8
→ git remote add xoebus git://github.com/xoebus/hub.git
→ git fetch xoebus
→ git cherry-pick 177eeb8
# `am` can be better than cherry-pick since it doesn't create a remote$ git am https://github.com/xoebus/hub/commit/177eeb8
# open the GitHub compare view between two releases$ git compare v0.9..v1.0
# put compare URL for a topic branch to clipboard$ git compare -u feature | pbcopy
# create a repo for a new project$ git init
$ git add . && git commit -m "It begins."$ git create -d "My new thing"→ (creates a new project on GitHub with the name of current directory)
$ git push origin master
#==============================##==============================## CMD GIT ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command github in a clear format. This allows users to quickly access the needed information for github without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for github are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the hg command with important options and switches using examples.
# ██╗ ██╗ ██████╗ # ██║ ██║██╔════╝ # ███████║██║ ███╗# ██╔══██║██║ ██║# ██║ ██║╚██████╔╝# ╚═╝ ╚═╝ ╚═════╝ # Clone a directoryhg clone
# Add files to hg trackerhg add filename
# Add all files in a folder to hg trackerhg add folder/
# Create a commit with all tracked changes and a messagehg commit -m "message"# Push commits to source repositoryhg push
# Pull changes from source repositoryhg pull
# Rebase local commits to disambiguate with remote repositoryhg pull --rebase
#==============================##==============================## CMD hg ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command hg in a clear format. This allows users to quickly access the needed information for hg without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for hg are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the ipython command with important options and switches using examples.
# ██╗██████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ ███╗ ██╗# ██║██╔══██╗╚██╗ ██╔╝╚══██╔══╝██║ ██║██╔═══██╗████╗ ██║# ██║██████╔╝ ╚████╔╝ ██║ ███████║██║ ██║██╔██╗ ██║# ██║██╔═══╝ ╚██╔╝ ██║ ██╔══██║██║ ██║██║╚██╗██║# ██║██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║# ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝# create a ipython profileipython profile create profile_name
# use specified profileipython --profile=${profile_name}# list objects, functions, etc. that have been added in the current namespace,# as well as modules that have been imported%who
# Assign a name to a set of input commands,# so that they can be executed all together using the assigned name%macro
# This will open an editor (whatever the shell variable EDITOR is set to, see above, or vi/vim if no variable is set)# containing the specified material, based on what arguments are provided,# and will execute that code once the editor is exited%edit
# This lists all ipython magic commands%lsmagic
# store variables, functions, etc. that you've defined in your .ipython/ipythonrc file for use in future sessions%store
# configure ipython to automatically open the python debugger pdb when an error occurs%pdb
# timing functions to see how long expressions take to execute%time
%timeit
# to log ipython input and/or output to files%logstart
%logon
%logoff
%logstate
# (to change directories, manipulate directory stacks, and create directory "bookmarks") %cd
%pushd
%popd
%bookmark
# Resets the interactive environment%reset
# Allows you to see any part of your input history%hist
# Search ("grep") through your history by typing%hist -g somestring
# List objects, functions, etc. that have been added in the current# namespace, as well as modules that have been imported%who
# Show internal IPython aliases%alias
# Embed ipython in python codefrom IPython import embed; embed()
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command ipython in a clear format. This allows users to quickly access the needed information for ipython without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for ipython are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the irb command with important options and switches using examples.
# ██╗██████╗ ██████╗ # ██║██╔══██╗██╔══██╗# ██║██████╔╝██████╔╝# ██║██╔══██╗██╔══██╗# ██║██║ ██║██████╔╝# ╚═╝╚═╝ ╚═╝╚═════╝ # interactive ruby. irb is a tool to execute interactively ruby expressions read from stdin# start irbirb
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command irb in a clear format. This allows users to quickly access the needed information for irb without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for irb are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the irssi command with important options and switches using examples.
# ██╗██████╗ ███████╗███████╗██╗# ██║██╔══██╗██╔════╝██╔════╝██║# ██║██████╔╝███████╗███████╗██║# ██║██╔══██╗╚════██║╚════██║██║# ██║██║ ██║███████║███████║██║# ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝╚═╝# To connect to an IRC server/connect <server domain name>
# To join a channel/join #<channel name># To set a nickname/nick <my nickname>
# To send a private message to a user/msg <nickname>
# To close the current channel window/wc
# To switch between channel windowsALT+<number>, eg. ALT+1, ALT+2
# To list the nicknames within the active channel/names
# To change the channel topic/topic <description>
# To limit channel background noise (joins, parts, quits, etc.)/ignore #foo,#bar JOINS PARTS QUITS NICKS # Quieten only channels `#foo`, `#bar`/ignore * JOINS PARTS QUITS NICKS # Quieten all channels# To save the current Irssi session config into the configuration file/save
# To quit Irssi/exit
#==============================##==============================## CMD IRSSI ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command irssi in a clear format. This allows users to quickly access the needed information for irssi without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for irssi are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the p4 command with important options and switches using examples.
# ██████╗ ██╗ ██╗# ██╔══██╗██║ ██║# ██████╔╝███████║# ██╔═══╝ ╚════██║# ██║ ██║# ╚═╝ ╚═╝# Print details related to Client and server configurationp4 info
# Open a file and add it to depotp4 add <filename>
#==============================##==============================## CMD P4 ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command p4 in a clear format. This allows users to quickly access the needed information for p4 without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for p4 are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the rcs command with important options and switches using examples.
# ██████╗ ██████╗███████╗# ██╔══██╗██╔════╝██╔════╝# ██████╔╝██║ ███████╗# ██╔══██╗██║ ╚════██║# ██║ ██║╚██████╗███████║# ╚═╝ ╚═╝ ╚═════╝╚══════╝# Initial check-in of file (leaving file active in filesystem)ci -u <filename>
# Check out with lockco -l <filename>
# Check in and unlock (leaving file active in filesystem)ci -u <filename>
# Display version x.y of a fileco -px.y <filename>
# Undo to version x.y (overwrites file active in filesystem with the specified revision)co -rx.y <filename>
# Diff file active in filesystem and last revisionrcsdiff <filename>
# Diff versions x.y and x.zrcsdiff -rx.y -rx.z <filename>
# View log of check-insrlog <filename>
# Break an RCS lock held by another person on a filercs -u <filename>
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command rcs in a clear format. This allows users to quickly access the needed information for rcs without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for rcs are a valuable resource to work efficiently and purposefully.
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the svn command with important options and switches using examples.
# ███████╗██╗ ██╗███╗ ██╗# ██╔════╝██║ ██║████╗ ██║# ███████╗██║ ██║██╔██╗ ██║# ╚════██║╚██╗ ██╔╝██║╚██╗██║# ███████║ ╚████╔╝ ██║ ╚████║# ╚══════╝ ╚═══╝ ╚═╝ ╚═══╝# update working copy from repositorysvn update "/path"# show changed files in working copysvn status
# show what changed in local filesvn diff "/path/filename"# add files or folderssvn add "path/item"# revert local uncommited changessvn revert "/path/file"# commit changes to reposvn commit -m "message""/path"# show help for 'svn diff'svn help diff
# Delete unversioned files in a Subversion checkout directory and all subdirectoriessvn st | grep ^? | sed -e 's/^? *//' | xargs -i{} echo rm -fr "{}"# Explanation: If there are no spaces in the file names, a simpler command will be enough. This one-liner works even if there are spaces and certain special characters in the file names.# svn st shows the changes in the Subversion checkout# | grep ^? matches only lines starting with question mark (= unversioned files)# | sed -e 's/^? *//' removes the question mark at the beginning of the line and the space characters following it# | xargs -i{} echo rm -fr "{}" executes an echo command for each line in the input, where the command is formed by inserting the input line in the {} placeholder. Confirm the result looks good and remove the echo to perform the rm.# Limitations: The command will not work with files that have " (double quote) in the name...# Add all unknown files in a Subversion checkoutsvn add . --force
# Explanation: Adding all unknown files in a working tree is usually very simple in other version control systems, for example: git add .
bzr add
# Not so simple in Subversion: svn add .
svn: warning: '.' is already under version control
# But if you add the --force flag, that will do! Keep in mind that this is not the same as: svn add * --force
# That would add not only unknown files, but ignored files too, which is probably not your intention. Make sure to specify directories explicitly, avoid using * with this command.# List the content of a GitHub repository without cloning itsvn ls https://github.com/user/repo/trunk/some/path
# Explanation: Git does not allow querying sub-directories of a repository. But GitHub repositories are also exposed as Subversion repositories, and Subversion allows arbitrary path queries using the ls command.# Notice the /trunk/ between the base URL of the repository and the path to query. This is due to the way GitHub provides Subversion using a standard Subversion repository layout, with trunk, branches and tags sub-directories.#==============================##==============================## CMD SVN ##==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command svn in a clear format. This allows users to quickly access the needed information for svn without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for svn are a valuable resource to work efficiently and purposefully.