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 tagged perl from sorted by
Terminal - Commands tagged perl - 174 results
perl -e 'my $in_comment = 0; while (<>) { $in_comment = 1 if m{\Q/*\E}; print if $in_comment; $in_comment = 0 if m{\Q*/\E}; }' *.cpp
2011-07-08 00:17:27
User: doherty
Functions: perl
1

This is a naive way of finding source code comments in source code files that use C-like comments: // and /*...*/

tail -f /var/log/squid/access.log | perl -p -e 's/^([0-9]*)/"[".localtime($1)."]"/e'
tail -f /var/log/logfile|perl -e 'while (<>) {$l++;if (time > $e) {$e=time;print "$l\n";$l=0}}'
2011-06-21 10:28:26
User: madsen
Functions: perl tail time
Tags: perl tail
2

Using tail to follow and standard perl to count and print the lps when lines are written to the logfile.

perl -MFile::Find -e"finddepth(sub{rmdir},'.')"
2011-05-23 08:45:34
User: igorfu
Functions: perl
Tags: perl delete
1

Recursively delete empty directories. Use with care.

rename 's/\d+/sprintf("%04d",$&)/e' *.jpg
2011-05-01 20:50:36
User: eightmillion
Functions: rename
11

This uses Perl's rename utility (you may have to call it as prename on your box) and won't choke on spaces or other characters in filenames. It will also zero pad a number even in filenames like "vacation-4.jpg".

perl -e 'rand($.) < 1 && ($line = $_) while <>;'
2011-04-25 21:28:26
Functions: perl
Tags: perl knuth
1

This is from perldoc -q random.*line, which says:

This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.

Who am I to argue with Don Knuth?

perl -ple 'BEGIN { $\ = "\r\n" }'
2011-03-01 09:45:37
Functions: perl
Tags: perl newline
0

Let -p do it's voodoo and do absolutely nothing but set the output record separator :-)

perl -ne 'print if !$a{$_}++'
2011-02-17 02:18:44
User: doherty
Functions: perl
3

Reads stdin, and outputs each line only once - without sorting ahead of time. This does use more memory than your system's sort utility.

(echo foobar; echo farboo) | perl -E 'say[sort<>=~/./g]~~[sort<>=~/./g]?"anagram":"not anagram"'
2011-02-17 02:15:46
User: doherty
Functions: echo perl
2

This works by reading in two lines of input, turning each into a list of one-character matches that are sorted and compared.

perl -MText::Highlight -E '$h=Text::Highlight->new(ansi=>1); my $text=do{local $/; open my $fh, "<", $ARGV[0]; <$fh>}; say $h->highlight("Perl", $text);' path/to/perl-file.pl
2011-01-31 05:52:43
User: doherty
Functions: perl
1

This uses Text::Highlight to output the specified Perl file with syntax highlighting. A better alternative is my App::perlhl - find it on the CPAN: http://p3rl.org/App::perlhl

grep -i "$*" /usr/lib/perl5/Unicode/CharName.pm | while read a b; do /usr/bin/printf "\u$a\tU+%s\t%s\n" "$b"; done
2011-01-04 11:30:16
User: ioggstream
Functions: grep read
1

No need for further filedes or substitution for splitting. Simply use read a b

egrep -i "^[0-9a-f]{4,} .*$*" $(locate CharName.pm) | while read h d; do /usr/bin/printf "\U$(printf "%08x" 0x$h)\tU+%s\t%s\n" $h "$d"; done
2010-12-31 16:47:59
User: hackerb9
Functions: egrep locate read
12

[Update! Thanks to a tip from ioggstream, I've fixed both of the bugs mentioned below.]

You, yes, 𝙔𝙊𝙐, can be the terror of the Internet! Why use normal, boring bullet points in your text, when you could use a ROTATED HEAVY BLACK HEART BULLET (❥)!? (Which would also be an awesome band name, by the way).



This script makes it easy to find unusual characters from the command line. You can then cut and paste them or, if you're using a GTK application, type Control+Shift+U followed by the code point number (e.g., 2765) and then a SPACE.



USAGE: Put this script in a file (I called mine "ugrep") and make it executable. Run it from the command line like so,



ugrep heart



The output will look like this,



☙ U+2619 REVERSED ROTATED FLORAL HEART BULLET

♡ U+2661 WHITE HEART SUIT

♥ U+2665 BLACK HEART SUIT

❣ U+2763 HEAVY HEART EXCLAMATION MARK ORNAMENT

❤ U+2764 HEAVY BLACK HEART

❥ U+2765 ROTATED HEAVY BLACK HEART BULLET

❦ U+2766 FLORAL HEART

❧ U+2767 ROTATED FLORAL HEART BULLET

⺖ U+2E96 CJK RADICAL HEART ONE

⺗ U+2E97 CJK RADICAL HEART TWO

⼼ U+2F3C KANGXI RADICAL HEART



You can, of course, use regular expressions. For example, if you are looking for the "pi" symbol, you could do this:



ugrep '\bpi\b'



REQUIREMENTS: Although this is written in Bash, it assumes you have Perl installed because it greps through the Perl Unicode character name module (/usr/lib/perl5/Unicode/CharName.pm). Note that it would not have made more sense to write this in Perl, since the CharName.pm module doesn't actually include a subroutine for looking up a character based on the description. (Weird.)



BUGS: In order to fit this script in the commandlinefu limits, a couple bugs were added. ① Astral characters beyond the BMP (basic multilingual plane) are not displayed correctly, but see below. ② Perl code from the perl module being grepped is sometimes extraneously matched.



MISFEATURES: Bash's printf cannot, given a Unicode codepoint, print the resulting character to the terminal. GNU's coreutils printf (usually "/usr/bin/printf") can do so, but it is brokenly pedantic about how many hexadecimal digits follow the escape sequence and will actually die with an error if you give the wrong number. This is especially annoying since Unicode code points are usually variable length with implied leading zeros. The CharNames.pm file represents BMP characters as 4 hexits, but astral characters as 5. In the actual version of this script that I use, I've kludged around this misfeature by zero-padding to 8 hexits like so,



/usr/bin/printf "\U$(printf "%08x" 0x$hex)"



TIP 1: The author recommends "xsel" for command line cut-and-paste. For example,



ugrep biohazard | xsel



TIP 2: In Emacs, instead of running this command in a subshell, you can type Unicode code points directly by pressing Control-Q first, but you'll likely want to change the default input from octal to hexadecimal. (setq read-quoted-char-radix 16).



TIP 3: Of course, if you're using X, and you want to type one of the more common unusual characters, it's easiest of all to do it with your Compose (aka Multi) key. For example, hitting [Compose] <3 types ♥.

cat /dev/urandom | hexdump -C | highlight ca fe 3d 42 e1 b3 ae f8 | perl -MTime::HiRes -pne "Time::HiRes::usleep(rand()*1000000)"
2010-12-29 21:26:18
User: doherty
Functions: cat hexdump perl
1

Nobody wants the boss to notice when you're slacking off. This will fill your shell with random data, parts of it highlighted. Note that 'highlight' is the Perl module App::highlight, not "a universal sourcecode to formatted text converter." You'll also need Term::ANSIColor.

pcregrep -r --exclude_dir='.svn' --include='.*jsp$' -A 2 -B 2 --color "pHtmlHome" .
2010-12-09 15:26:07
User: hute37
Tags: perl grep
0

range context (-A -B) search, with exclusion of vcs directories

perl -e 'for(;;){@d=split("",`date +%H%M%S`);print"\r";for(0..5){printf"%.4b ",$d[$_]}sleep 1}'
2010-12-04 00:05:54
User: putnamhill
Functions: perl
9

Fun idea! This one adds seconds and keeps running on the same line. Perl's probably cheating though. :)

perl -pe 'eof()||s/\n/<SOMETEXT>/g' file.txt
2010-12-02 01:19:27
User: eightmillion
Functions: perl
3

This command turns a multi-line file into a single line joined with <SOMETEXT>. To skip blank lines, use:

perl -pe '(eof()||s/^\s*$//)||s/\n/<SOMETEXT>/g' file.txt
find . -type f -print0 | xargs -0 perl -pi.save -e 'tr/A-Z/a-z/'
2010-11-25 13:55:34
User: depesz
Functions: find perl xargs
Tags: perl find regex
1

In this way it doesn't have problems with filenames with spaces.

perl -e "tr/[A-Z]/[a-z]/;" -pi.save $(find . -type f)
pcharc(){ perl -e 'for (0..255) {$_ = chr($_); print if /['$1']/}' | cat -v; echo;}
2010-11-13 00:32:41
User: putnamhill
Functions: cat perl
Tags: perl
1

Today I needed a way to print various character classes to use as input for a program I was writing. Also a nice way to visualize character classes.

pcregrep --color -M -N CRLF "owa_pattern\.\w+\W*\([^\)]*\)" source.sql
git status | perl -F'\s' -nale 'BEGIN { $a = 0 }; $a = 1 if $_ =~ /changed but not updated/i; print $F[-1] if ( $a && -f $F[-1] )'
2010-10-15 07:58:14
Functions: perl
Tags: status git perl
0

Parse the output of git status.

Once the line '# Changed but not updated:' has passed print every last part of the line if it exists on disk.

diff <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file1) <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file2)
2010-10-06 19:14:42
User: jemptymethod
Functions: diff perl
Tags: bash diff perl
2

**NOTE** Tekhne's alternative is much more succinct and its output conforms to the files actual contents rather than with white space removed

My command on the other hand uses bash process substitution (and "Minimal" Perl), instead of files, to first remove leading and trailing white space from lines, before diff'ing the streams. Very useful when differences in indentation, such as in programming source code files, may be irrelevant

find . -iname '*.jpg' -type f -print0 |perl -0 -ne '$a+=-s $_;END{print "$a\n"}'
2010-09-12 13:14:12
Functions: find perl
1

This deals nicely with filenames containing special characters and can deal with more files than can fit on a commandline. It also avoids spawning du.

perl -le 'chomp($w=`which $ARGV[0]`);$_=`file $w`;while(/link\b/){chomp($_=(split/`/,$_)[1]);chop$_;$w.=" -> $_";$_=`file $_`;}print "\n$w";' COMMAND_NAME
2010-07-30 19:26:35
User: dbbolton
Functions: perl
0

This will show you any links that a command follows (unlike 'file -L'), as well as the ultimate binary or script.

Put the name of the command at the very end; this will be passed to perl as the first argument.

For obvious reasons, this doesn't work with aliases or functions.

echo "text" | hd