Commands using perl (369)

  • 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?


    1
    perl -e 'rand($.) < 1 && ($line = $_) while <>;'
    unixmonkey20842 · 2011-04-25 21:28:26 3
  • Can also just use the debug mode like this. Show Sample Output


    1
    perl -dwe 1
    bashrc · 2011-05-05 20:28:03 6
  • Replace PACKAGE with desired package name. Found here: http://mikebeach.org/2011/04/undo-apt-get-build-dep/


    1
    sudo aptitude markauto $(apt-cache showsrc PACKAGE | grep Build-Depends | perl -p -e 's/(?:[\[(].+?[\])]|Build-Depends:|,|\|)//g')
    Lexton · 2011-05-08 14:18:52 6
  • Recursively delete empty directories. Use with care.


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

  • 1
    arp-scan -I eth0 -l | perl -ne '/((\d{1,3}\.){3}\d{1,3})/ and $ip=$1 and $_=`nmblookup -A $ip` and /([[:alnum:]-]+)\s+<00>[^<]+<ACTIVE>/m and printf "%15s %s\n",$ip,$1'
    bandie91 · 2011-07-08 07:41:41 3

  • 1
    perl -mText::Highlight -E 'say Text::Highlight->new(ansi => 1)->highlight(Perl => do { local (@ARGV,$/) = shift; <> }) ' path/to/perl-file.pl
    dbr · 2011-07-12 04:55:12 5
  • this command example converts to 25 fps subtitles that were originally created for 24 fps movie


    1
    cat subtitles.txt | perl -pe 's/} /}/g; s/{(\d+)}/=1=/; $f1=(24/25*$1); s/{(\d+)}/=2=/; $f2=(24/25*$1); $f1=~s/\..*//; $f2=~s/\..*//; s/=1=/{$f1}/; s/=2=/{$f2}/; ' > subtitles_newfps.txt
    ciekawy · 2011-07-30 15:34:43 18
  • Calls the POSIX strerror() function to look up the meaning of integer ERRNOs set by some functions.


    1
    perl -MPOSIX -e 'print strerror($ARGV[0])."\n";' ERRNO
    sethjust · 2011-09-21 18:16:19 5

  • 1
    perl -i -pe 'BEGIN{undef $/;} s/START.*?STOP/replace_string/smg' file_to_change
    hute37 · 2011-10-05 11:22:36 10
  • the output of svn log is annoying to grep, since it spreads the useful info over multiple lines. This compacts the output down to one line so eg you can grep for a comment and see the rev, date & committer straight away. Updated: MUCH shorter, easier to remember. Now it just replaces newlines with spaces, except on '---' lines. Show Sample Output


    1
    svn log | perl -l40pe 's/^-+/\n/'
    bazzargh · 2011-10-14 16:02:22 5

  • 1
    perl -ane 'END{printf(" %d %d %d\n", $x, $y, $z)} $x+=1; $y+=@F; $z+=length' file.txt
    kev · 2011-10-24 06:14:02 10
  • The crypt function takes a password, key, as a string, and a salt character array which is described below, and returns a printable ASCII string which starts with another salt. It is believed that, given the output of the function, the best way to find a key that will produce that output is to guess values of key until the original value of key is found. from http://en.wikipedia.org/wiki/Crypt_(Unix)


    1
    useradd -m -p $(perl -e'print crypt("passwordscelta", "stigghiola")') user
    0disse0 · 2012-02-06 19:53:01 7
  • This one line Perl script will display the smallest to the largest files sizes in all directories on a server. Show Sample Output


    1
    du -k | sort -n | perl -ne 'if ( /^(\d+)\s+(.*$)/){$l=log($1+.1);$m=int($l/log(1024)); printf ("%6.1f\t%s\t%25s %s\n",($1/(2**(10*$m))),(("K","M","G","T","P")[$m]),"*"x (1.5*$l),$2);}' | more
    Q_Element · 2012-02-07 15:49:19 10
  • Requires perl 5.14 or greater


    1
    perl -e 'rename $_, s/ /-/gr for <*.mp3>'
    ironcamel · 2012-02-21 17:07:18 3
  • This prints file access rights in octal - useful when "stat" is unavailable. Show Sample Output


    1
    perl -e 'printf "%04o\n", (stat shift)[2] & 0777;' file
    zlemini · 2012-03-22 15:05:04 9
  • extract data in multiline blocks of data with perl pattern matching loop Show Sample Output


    1
    cat z.log | perl -ne 'BEGIN{ print "DATE;RATE\n"; } /\[(\d.*)\]/ && print $1; /CURRENT RATE: +(\S+) msg.*/ && print ";" .$1 . "\n"; '
    hute37 · 2012-04-03 13:52:20 3

  • 1
    perl -e 'printf "00:16:3E:%02X:%02X:%02X\n", rand 0xFF, rand 0xFF, rand 0xFF'
    Gular · 2012-07-02 09:59:43 4
  • Really helpfull when play with files having spaces an other bad name. Easy to store and access names and path in just a field while saving it in a file. This format (URL) is directly supported by nautilus and firefox (and other browsers) Show Sample Output


    1
    convert_path2uri () { echo -n 'file://'; echo -n "$1" | perl -pe 's/([^a-zA-Z0-9_\/.])/sprintf("%%%.2x", ord($1))/eg' ;} #convert2uri '/tmp/a b' ### convert file path to URI
    totti · 2013-07-01 08:54:45 7
  • Sets the @ A record for your domain hosted by namecheap to your current internet-facing IP address, logs success or failure with syslog, and logs the data returned to /root/dnsupdate. Change the XXX's as appropriate. More info at: http://www.namecheap.com/support/knowledgebase/article.aspx/29/ Show Sample Output


    1
    logger -tdnsupdate $(curl -s 'https://dynamicdns.park-your-domain.com/update?host=@&domain=xxx&password=xxx'|tee -a /root/dnsupdate|perl -pe'/Count>(\d+)<\/Err/;$_=$1eq"0"?"Update Sucessful":"Update failed"'&&date>>/root/dnsupdate)
    MagisterQuis · 2013-08-11 16:27:39 7
  • Use it to send raw data to a networked device. Used to interact with relay controller board whose documentation is lost, so use wireshark to sniff the sent data and replayed using the command.


    1
    echo -n 023135 | perl -pe 's/([0-9a-f]{2})/chr hex $1/gie' | nc -4u -q1 -p5001 192.168.0.100 2000
    sucotronic · 2013-09-18 14:31:47 7
  • Converts control codes and spaces (ASCII code ≤ 32) to visible Unicode Control Pictures, U+2400 ? U+2420. Skips \n characters, which is probably a good thing. Show Sample Output


    1
    /bin/echo -e '\002Hello, Folks\t!\r' | perl -pwle 'use v5.14; s/([\N{U+0000}-\N{U+0020}])/chr(9216+ord($1))/ge;'
    scruss · 2014-06-30 01:45:40 11
  • An advantage is that this doesn't modify remained string at all. One can change {0,1} with {0,n} to drop several columns


    1
    perl -pE's/(\S+\s*){0,1}//'
    pung96 · 2015-05-09 15:14:58 11
  • Better than the others, and actually works unlike some of them. Show Sample Output


    1
    objdump -d $1 | grep -Po '\s\K[a-f0-9]{2}(?=\s)' | sed 's/^/\\x/g' | perl -pe 's/\r?\n//' | sed 's/$/\n/'
    Daytona · 2015-05-23 01:21:58 10

  • 1
    echo "quit" | openssl s_client -connect facebook.com:443 | openssl x509 -noout -text | grep "DNS:" | perl -pe "s/(, )?DNS:/\n/g"
    lgarron · 2015-08-13 22:50:45 9

  • 1
    find . -type f | perl -ne 'print $1 if m/\.([^.\/]+)$/' | sort -u
    wuseman1 · 2018-11-11 01:09:42 503
  • ‹ First  < 5 6 7 8 9 >  Last ›

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. 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.

Share Your Commands


Check These Out

Calculate the distance between two geographic coordinates points (latitude longitude)
The Haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes.

Convert seconds to [DD:][HH:]MM:SS
Converts any number of seconds into days, hours, minutes and seconds. sec2dhms() { declare -i SS="$1" D=$(( SS / 86400 )) H=$(( SS % 86400 / 3600 )) M=$(( SS % 3600 / 60 )) S=$(( SS % 60 )) [ "$D" -gt 0 ] && echo -n "${D}:" [ "$H" -gt 0 ] && printf "%02g:" "$H" printf "%02g:%02g\n" "$M" "$S" }

Download all images from a 4chan thread
Useful for ripping wallpaper from 4chan.org/wg

ssh to machine behind shared NAT
Useful to get network access to a machine behind shared IP NAT. Assumes you have an accessible jump host and physical console or drac/ilo/lom etc access to run the command. Run the command on the host behind NAT then ssh connect to your jump host on port 2222. That connection to the jump host will be forwarded to the hidden machine. Note: Some older versions of ssh do not acknowledge the bind address (0.0.0.0 in the example) and will only listen on the loopback address.

Show the UUID of a filesystem or partition
Show the UUID-based alternate device names of ZEVO-related partitions on Darwin/OS X. Adapted from the lines by dbrady at http://zevo.getgreenbytes.com/forum/viewtopic.php?p=700#p700 and following the disk device naming scheme at http://zevo.getgreenbytes.com/wiki/pmwiki.php?n=Site.DiskDeviceNames

Get your external IP address without curl
Curl is not installed by default on many common distros anymore. wget always is :) $ wget -qO- ifconfig.me/ip

Copy one file to multiple files
Copies file.org to file.copy1 ... file.copyn

power off system in X hours form the current time, here X=2

generate a unique and secure password for every website that you login to
usage: sitepass MaStErPaSsWoRd example.com description: An admittedly excessive amount of hashing, but this will give you a pretty secure password, It also eliminates repeated characters and deletes itself from your command history. tr '!-~' 'P-~!-O' # this bit is rot47, kinda like rot13 but more nerdy rev # this avoids the first few bytes of gzip payload, and the magic bytes.

Route outbound SMTP connections through a addtional IP address rather than your primary


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: