Hide

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again.

Delete that bloated snippets file you've been using and share your personal repository with the world. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.


If you have a new feature suggestion or find a bug, please get in touch via http://commandlinefu.uservoice.com/

Get involved!

You can sign-in using OpenID credentials, or register a traditional username and password.

First-time OpenID users will be automatically assigned a username which can be changed after signing in.

Hide

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for:

Hide

News

2011-03-12 - Confoo 2011 presentation
Slides are available from the commandlinefu presentation at Confoo 2011: http://presentations.codeinthehole.com/confoo2011/
2011-01-04 - Moderation now required for new commands
To try and put and end to the spamming, new commands require moderation before they will appear on the site.
2010-12-27 - Apologies for not banning the trolls sooner
Have been away from the interwebs over Christmas. Will be more vigilant henceforth.
2010-09-24 - OAuth and pagination problems fixed
Apologies for the delay in getting Twitter's OAuth supported. Annoying pagination gremlin also fixed.
Hide

Tags

Hide

Functions

Commands using printf from sorted by
Terminal - Commands using printf - 150 results
MYURL=http://test.example.com ; awk -F/ '{ print $3 }' <<< $MYURL | awk -F. '{ if ( $(NF-1) == "co" || $(NF-1) == "com" ) printf $(NF-2)"."; print $(NF-1)"."$(NF); }'
2014-05-26 07:31:40
User: snafu
Functions: awk printf
Tags: bash url domain
0

Extracts domain and subdomain from given URl. See examples.

lspci -vv | grep 'Ethernet\|Serial' | awk 'NR == 1{ printf $1 } NR == 2 { print " mac " $7 }' | sed ?e 's/-/:/g' -e 's/:f[ef]:f[ef]//g' -e 's/01:00.0/eth0/g' -e 's/01:00.1/eth1/g' -e 's/01:00.2/eth2/g' -e 's/01:00.3/eth3/g' > /etc/iftab && ifrename
2014-03-01 20:07:18
User: PROJAK_SX
Functions: awk grep lspci printf sed
0

for redhat systems works sometimes :S tested on dell poweredge r7+ systems

printf -- " -e %s" ${ARRAY[*]}
2014-02-25 03:34:12
User: SEJeff
Functions: printf
1
DOCKER_APP_VARS=(DATABASE_USER=dbuserro, DATABASE_PASSWORD=maipass)

[jeff@omniscience container] (master)$ echo docker run $(printf -- " -e %s" ${DOCKER_APP_VARS[*]}) -name 12factorapp mattdm/fedora-small

docker run -e DATABASE_USER=dbuserro, -e DATABASE_PASSWORD=maipass -name 12factorapp mattdm/fedora-small

Note that the printf method by itsself doesn't include a newline (\n), so you'll need to embed it into an echo statement or something that does.

function b58encode () { local b58_lookup_table=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z}); bc<<<"obase=58;ibase=16;${1^^}"|(read -a s; for b58_index in "${s[@]}" ; do printf %s ${b58_lookup_table[ 10#"$b58_index" ]}; done); }
4

A bitcoin "brainwallet" is a secret passphrase you carry in your brain.

The Bitcoin Brainwallet Private Key Base58 Encoder is the third of three functions needed to calculate a bitcoin PRIVATE key from your "brainwallet" passphrase.

This base58 encoder uses the obase parameter of the amazing bc utility to convert from ASCII-hex to base58. Tech note: bc inserts line continuation backslashes, but the "read s" command automatically strips them out.

I hope that one day base58 will, like base64, be added to the amazing openssl utility.

function brainwallet_exponent () { printf %s "$1"|sha256sum|head -c 64; }
2014-02-18 01:49:09
User: nixnax
Functions: head printf
4

A bitcoin "brainwallet" is a secret passphrase you carry in your brain.

The Bitcoin Brainwallet Exponent Calculator is one of three functions needed to calculate the bitcoin PRIVATE key. Roughly, the formula is exponent = sha256 (passphrase)

Note that this is a bash function, which means you have to type its name to invoke it.

You can check the accuracy of the results here http://brainwallet.org

YYYY=2014; MM=02; for d in $(cal $MM $YYYY | grep "^ *[0-9]"); do DD=$(printf "%02d" $d); echo $YYYY$MM$DD; done
2014-02-06 11:31:57
User: fibo
Functions: cal echo grep printf
Tags: cal for loop
1

Edit YYYY and MM at the beginning of the command with the year and month you want.

Note that `DD=$(printf "%02d" $d)` will pad single digit integers with a leading zero.

Substitute `echo $YYYY$MM$DD` at the end of the line with the command you want to launch, for instance

script.pl --yyyymmdd $YYYY$MM$DD

prepend () { array=("$@"); len=${#array[@]}; file=${array[$len-1]}; text=${array[@]:0:$len-1}; printf '%s\n' 0a "$text" . w | ed -s "$file"; }
2013-12-09 21:59:26
User: zlemini
Functions: ed printf
Tags: sed replace
3

Syntax:

$ prepend content to add [filename]

Uses ed, so no temp files created.

yes 'c=(" " " " " " 0 1); printf "${c[RANDOM%5]}"' | bash
for m in `df -P | awk -F ' ' '{print $NF}' | sed -e "1d"`;do n=`df -P | grep "$m$" | awk -F ' ' '{print $5}' | cut -d% -f1`;i=0;if [[ $n =~ ^-?[0-9]+$ ]];then printf '%-25s' $m;while [ $i -lt $n ];do echo -n '=';let "i=$i+1";done;echo " $n";fi;done
2013-07-29 20:12:39
User: drockney
Functions: awk cut echo grep printf sed
Tags: bash
5

Automatically drops mount points that have non-numeric sizes (e.g. /proc). Tested in bash on Linux and AIX.

while read X ; do printf "$X --"; virsh dumpxml $X | egrep "source dev|source file"; done< <(virsh list | awk '$1 ~ /^[1-9]/ { print $2 }')
2013-07-29 17:32:59
User: hugme
Functions: awk egrep printf read
0

This will strip out the relivent disk information from kvm. I'm using it to find disks on a SAN which are no longer in use.

printf "\ec"
2013-05-29 18:10:22
User: soroosh
Functions: printf
0

clear command doesn't actually clear the terminal because if you scroll you can still see output from the previous commands. Using this command you can clear your terminal screen as well as buffer.

alias clearscrollback='clear;printf %b "\033[3J"'
count='1'; for i in *.jpg; do mv $i $(printf '%01d'.jpg $count); (( count++ )); done
2013-02-20 06:38:25
User: lalanza808
Functions: mv printf
-1

The '1' in '%01d' changes the amounts of digits in the integer, eg. 1 vs 0001.

awk '{for (i=9;i<=NF;i++) {printf "%s",$i; printf "%s", " ";}; printf "\n"}'
2013-02-12 13:57:43
User: adimania
Functions: awk printf
Tags: awk
0

It'll print the file names preserving the spaces in their names and adding new line after every new filename.

I wrote this to quickly find out how many files in any directory is owned by a particular user. This can be extended using pipe and grep to do much more.

find . -name '*.jpg' | awk 'BEGIN{ a=0 }{ printf "mv %s name%01d.jpg\n", $0, a++ }' | bash
2013-02-07 06:12:37
User: doublescythe
Functions: awk find printf
0

This command will take the files in a directory, rename them, and then number them from 1...N.

Black belt stuff.

Hell of a time saver.

today() { printf '%(%Y-%m-%d)T\n' -1; } ## bash-4
function up { cd $(eval printf '../'%.0s {1..$1}) && pwd; }
2013-01-21 12:57:45
User: michelsberg
Functions: cd eval printf
Tags: cd directory
5

Usage:

up N

I did not like two things in the submitted commands and fixed it here:

1) If I do cd - afterwards, I want to go back to the directory I've been before

2) If I call up without argument, I expect to go up one level

It is sad, that I need eval (at least in bash), but I think it's safe here.

eval is required, because in bash brace expansion happens before variable substitution, see http://rosettacode.org/wiki/Repeat_a_string#Using_printf

while(true); do printf "%s\f" $(date +%T); sleep 1; done | sm -
2013-01-14 17:13:34
User: claudius
Functions: date printf sleep
Tags: time clock sm
1

http://www.joachim-breitner.de/projects#screen-message now also supports reading stdin continuously to update what it shows, different ?slides? separated by a form feed character. Here, we feed the current time into it each second to create a large clock.

for code in $(seq -w 0 255); do for attr in 0 1; do printf "%s-%03s %bTest%b\n" "${attr}" "${code}" "\e[${attr};38;05;${code}m" "\e[m"; done; done | column -c $((COLUMNS*2))
2013-01-13 18:23:44
User: claudius
Functions: column printf seq
Tags: bash color colors
0

Shows the ?rendering? for each of the 256 colours in both the bold and normal variant. Using seq is helpful to get even lines, passing $((COLUMNS*2)) to column sort-of-handles the nonprintable characters.

tshark -r *.eth -S -R "ajp13" -d tcp.port==9009,ajp13 -s 0 -l -V | awk '/Apache JServ/ {p=1} /^ *$/ {p=0;printf "\n"} (p){printf "%s\n", $0} /^(Frame|Internet Pro|Transmission Control)/ {print $0}'
2013-01-10 21:12:51
User: tsureshkumar
Functions: awk printf
Tags: tshark
0

if you have a capture file *.eth, and ajp protocol is in use on port 9009, you can paste the above command. You can change the fiile and port name

du . | sort -nr | awk '{split("KB MB GB TB", arr); idx=1; while ( $1 > 1024 ) { $1/=1024; idx++} printf "%10.2f",$1; print " " arr[idx] "\t" $2}' | head -25
2012-12-03 02:59:13
User: agas
Functions: awk du head printf sort
0

Lists the size in human readable form and lists the top 25 biggest directories/files

while true; do printf "\e[32m%X\e[0m" $((RANDOM%2)); for ((i=0; i<$((RANDOM%128)); i++)) do printf " "; done; done
2012-11-27 10:40:42
User: seb1245
Functions: printf
0

Unlike other alternatives, this command only relies on bash builtins and should also work on windows platforms with the bash executable.

Sparseness corresponds to the number 128 and can be adjusted. To print all possible digits instead of only 0 and 1 replace RANDOM%2 by RANDOM%10 or RANDOM%16 to add letters [A-F].

hl-nonprinting () { local C=$(printf '\033[0;36m') B=$(printf '\033[0;46m') R=$(printf '\033[0m') np=$(env printf "\u00A0\uFEFF"); sed -e "s/\t/${C}&#9657;&$R/g" -e "s/$/${C}&#8267;$R/" -e "s/[$np]/${B}& $R/g";}
2012-11-07 10:09:40
User: unhammer
Functions: env printf sed
-1

Can't see it here, but the non-breaking space is highlighted :)

Of course,

cat -t -e

achieves something similar, but less colourful.

Could add more code points from https://en.wikipedia.org/wiki/Space_%28punctuation%29#Spaces_in_Unicode

hl-nonprinting () { local C=$(printf '\033[0;36m') R=$(printf '\033[0m'); sed -e "s/\t/${C}&#9657;&$R/g" -e "s/$/${C}&#8267;$R/";}
2012-11-07 09:55:48
User: unhammer
Functions: printf sed
-1

I don't think it's possible to give a (background) colour to the tab itself, since a tab is, IIUC, simply a command to the terminal to move to the right. Nevertheless, this "highlighting" can be helpful when working with tab-separated files.

for i in `ls /var/log/sa/|grep -E "sa[0-9][0-9]"`;do echo -ne "$i -- ";sar -r -f /var/log/sa/$i|awk '{ printf "%3.2f\n",($4-$6-$7)*100/(3+$4)}'|grep -Eiv "average|linux|^ --|0.00|^-" |awk '{sum+=$1 }END{printf "Average = %3.2f%%\n",sum/NR}';done