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 awk from sorted by
Terminal - Commands using awk - 1,149 results
ps -eo user,pcpu,pmem | tail -n +2 | awk '{num[$1]++; cpu[$1] += $2; mem[$1] += $3} END{printf("NPROC\tUSER\tCPU\tMEM\n"); for (user in cpu) printf("%d\t%s\t%.2f\t%.2f\n",num[user], user, cpu[user], mem[user]) }'
2009-10-29 12:49:01
User: georgz
Functions: awk ps tail
7

The original version gives an error, here is the correct output

TIMEUNIT=$(awk '/timescale/{print NR}' a)
TIMEUNIT=$( cat a | grep -n "timescale" | awk -F ":" '{ print $1 } ' )
awk 'BEGIN {for(i=1;i<=100;i++)sum+=i}; END {print sum}' /dev/null
2009-10-26 18:24:57
User: dennisw
Functions: awk
Tags: awk
0

Calculating series with awk only, no need for seq: add numbers from 1 to 100

Variations:

1+3+...+(2n-1) = n^2

awk 'BEGIN {for(i=1;i<=19;i+=2)sum+=i}; END {print sum}' /dev/null # displays 100

1/2 + 1/4 + ... = 1

awk 'BEGIN {for(i=1;i<=10;i++)sum+=1/(2**i)}; END {print sum}' /dev/null # displays 0.999023
calc(){ awk "BEGIN{ print $* }" ;}
2009-10-23 06:03:07
User: twfcc
Functions: awk
12

simple function , floating point number is supported.

awk 'BEGIN{dir=DIR?DIR:ENVIRON["PWD"];l=split(dir,parts,"/");last="";for(i=1;i<l+1;i++){d=last"/"parts[i];gsub("//","/",d);system("ls -ld \""d"\"");last=d}}'
2009-10-22 16:28:07
User: arcege
Functions: awk
-1

Handled all within awk. Takes the value from $PWD and constructs directory structures and runs commands against them. The gsub() call is not necessary, but added for better visibility.

If a variable DIR is given on the awk command-line, then that directory is used instead:

awk -vDIR=$HOME/.ssh 'BEGIN{dir=DIR?...}'
awk 'FNR==5' <file>
2009-10-20 22:52:41
User: dennisw
Functions: awk
1

Just one character longer than the sed version ('FNR==5' versus -n 5p). On my system, without using "exit" or "q", the awk version is over four times faster on a ~900K file using the following timing comparison:

testfile="testfile"; for cmd in "awk 'FNR==20'" "sed -n '20p'"; do echo; echo $cmd; eval "$cmd $testfile"; for i in {1..3}; do time for j in {1..100}; do eval "$cmd $testfile" >/dev/null; done; done; done

Adding "exit" or "q" made the difference between awk and sed negligible and produced a four-fold improvement over the awk timing without the "exit".

For long files, an exit can speed things up:

awk 'FNR==5{print;exit}' <file>
awk '{if (NR == 3) print}' <file>
2009-10-19 15:58:09
User: yooreck
Functions: awk
-5

I don't know if it's better but works fine :)

for i in $(netstat --inet -n|grep ESTA|awk '{print $5}'|cut -d: -f1);do geoiplookup $i;done
2009-10-18 20:41:47
Functions: awk cut grep netstat
3

Sample command to obtain a list of geographic localization for established connections, extracted from netstat. Need geoiplookup command ( part of geoip package under CentOS)

for file in *.iso; do mkdir `basename $file | awk -F. '{print $1}'`; sudo mount -t iso9660 -o loop $file `basename $file | awk -F. '{print $1}'`; done
HDD=$(df | awk ' NR>3 (S=$5) (M=$6) { if (S>90) print "Your Systems "M" is """S" Full" } ') ; [[ $HDD ]] && echo "$HDD" | mail -s "Hard-Drives Full" TO@EMAIL.com -- -f FROM@EMAIL.com >/dev/null
seq 4|xargs -n1 -i bash -c "echo -n 164.85.216.{} - ; nslookup 164.85.216.{} |grep name"|tr -s ' ' ' '|awk '{print $1" - "$5}'|sed 's/.$//'
URL=[target.URL]; curl -q -d "url=$URL" http://untr.im/api/ajax/api | awk -F 'href="' '{print $3}' | awk -F '" rel="' '{print $1}'
find . -type d -print | sed -e 's;[^/]*/;..........;g'|awk '{print $0"-("NR-1")"}'
awk '{print length, $0;}' | sort -nr
awk '{print(substr($0,1,5))}' file
2009-10-05 18:58:49
Functions: awk
-2

Consider this file :

laminate

this

file

with awk

hello to

commandlinefu

I can use awk substring to laminate words :

lamin

this

file

with

hello

comma

Similar to http://www.commandlinefu.com/commands/view/2000/laminate-files-line-by-line

egrep 'Failed password for invalid' /var/log/secure | awk '{print $13}' | uniq
2009-10-04 18:08:13
Functions: awk egrep
1

Work for me on CentOS, grep and print ip addresses of ssh bruteforce attempts

dmidecode | awk '/VMware Virtual Platform/ {print $3,$4,$5}'
2009-09-25 14:46:35
User: SuperFly
Functions: awk
6

If you run this command on a VMWare Virtual Machine, it will return the string "VMware Virtual Platform". If you run it on a physical machine, it will return nothing. Useful for having a script determine if it's running on a VM or not. Of course, you must have dmidecode installed for this to work.

Try it this way in a script: ISVM=$(dmidecode | awk '/VMware Virtual Platform/ {print $3,$4,$5}')

Then test if $ISVM has text in it, or is blank.

find [path] [expression] -exec du -ab {} \; | awk '{total+=$0}END{print total}'
mplayer -vo dummy -ao dummy -identify * 2>&1 | grep ID_LENGTH | sed 's/.*=\([0-9]*\)/\1/' | xargs echo | sed 's/ /+/g' | bc | awk 'S=$1; {printf "%dh:%dm:%ds\n",S/(60*60),S%(60*60)/60,S%60}'
2009-09-24 10:33:19
User: Strawp
Functions: awk bc echo grep sed xargs
5

You're behind on your TV catch-up, but how far behind? This command tries to open mplayer against all files in the current dir. If it's a video file it will contain ID_LENGTH, which is summed and output in hours, minutes and seconds.

Someone better at awk could probably reduce this down a lot.

(echo "set terminal png;plot '-' u 1:2 t 'cpu' w linespoints;"; sudo vmstat 2 10 | awk 'NR > 2 {print NR, $13}') | gnuplot > plot.png
awk '{$1=""; print}'
vmstat 2 10 | awk 'NR > 2 {print NR, $13}' | gnuplot -e "set terminal png;set output 'v.png';plot '-' u 1:2 t 'cpu' w linespoints;"
$ awk '{printf "select * from table where id = %c%s%c;\n",39,$1,39; }' inputfile.txt
2009-09-21 14:08:04
User: alvinx
Functions: awk
2

inputfile.txt is a space-separated textfile, 1st column contains the items (id) I want to put into my SQL statement.

39 = charactercode for single tick '

1 = first column

If inputfile.txt is a CSV-file separated by "," use FS= to define your own field-separator:

awk 'BEGIN {FS=","; }{printf "select * from table where id = %c%s%c;\n",39,$1,39; }' inputfile.txt
netstat -an | awk '$1 ~ /[Tt][Cc][Pp]/ && $NF ~ /ESTABLISHED/{i++}END{print "Connected:\t", i}'