Commands using perl (368)

  • Using perl and tput, show all the colors with numbers that your actual $TERM can handle. If want to remove the numbers at beginning of new line, it should be something like this: perl -E 'say `tput setb $_`," "x `tput cols`, `tput sgr0` for 0 .. (`tput colors` - 1)'

    perl -E 'say $_,`tput setb $_`," "x(`tput cols`-length("$_")),`tput sgr0` for 0..(`tput colors`-1)'
    MarxBro · 2012-11-22 01:55:51 0
  • changes THIS to THAT in all files matching fileglob* without using secondary files

    perl -pi -e 's/THIS/THAT/g' fileglob*
    elofland · 2009-02-05 19:19:52 4

  • 2
    perl -pe 's/.+;//' ~/.zsh_history | sort | uniq -c | sort -r|head -10
    aoiaoi · 2009-02-06 15:24:32 0

  • 2
    perl -pe 's/\d+/++$n/e' file.txt
    mikeda · 2009-02-17 14:51:31 0
  • Insert a comma where necessary when counting large numbers. I needed to separate huge amounts of packets and after 12+ hours of looking in a terminal, I wanted it in readable form. Show Sample Output

    perl -pe '$_=reverse;s/\d{3}(?=\d)(?!.*?\.)/$&,/g;$_=reverse'
    sil · 2009-02-18 16:34:18 0
  • Finds the string in every file in an entire directory and all its subdirectories and replaces it with a new string. Especially useful when changing a machine's IP address or hostname - run it on /etc.

    perl -pi -e's/<what to find>/<what to replace it with>/g' `grep -Rl <what to find> /<dir>/*`
    adampbell · 2009-02-26 19:14:39 2

  • 2
    find $HOME -type f -print | perl -wnlaF'/' -e 'BEGIN{ print "#EXTM3U"; } /.+\.wmv$|.+\.mpg$|.+\.vob$/i and print "#EXTINF:$F[-1]\nfile://$&";' > movies.m3u
    ishiduca · 2009-02-28 12:17:41 0

  • 2
    perl -ne 'while (/([0-9]+\.){3}[0-9]+/g) {print "$&\n"};' file.txt
    P17 · 2009-04-01 13:49:46 2
  • There was another line that was dependent on having un-named screen sessions. This just wouldn't do. This one works no matter what the name is. A possible improvement would be removing the perl dependence, but that doesn't effect me.

    for i in `screen -ls | perl -ne'if(/^\s+\d+\.([^\s]+)/){print $1, " "}'`; do gnome-terminal -e "screen -x $i"; done
    hank · 2009-04-25 22:39:24 1
  • Replace 'this' with 'that'

    perl -p -i -e 's/this/that/g' filename
    rader5 · 2009-08-09 20:53:50 5
  • When you have one of those (log)files that only has epoch for time (since no one will ever look at them as a date) this is a way to get the human readable date/time and do further inspection. Mostly perl-fu :-/

    perl -F' ' -MDate::Format -pale 'substr($_, index($_, $F[1]), length($F[1]), time2str("%C", $F[1]))' file.log
    coffeeaddict_nl · 2009-08-13 13:57:33 0

  • 2
    perl -e 'print scalar(gmtime(1234567890)), "\n"'
    andrew112358 · 2009-08-25 15:00:52 1

  • 2
    wget 'link of a Picasa WebAlbum' -O - |perl -e'while(<>){while(s/"media":{"content":\[{"url":"(.+?\.JPG)//){print "$1\n"}}' |wget -w1 -i -
    aciancone · 2009-09-27 14:36:27 0
  • Once I wrote a command line calculator program in C, then I found this... and added to it a bit. For ease of use I normally use this in a tiny Perl program (which I call pc for 'Perl Calculator') #!/usr/bin/perl -w die "Usage: $0 MATHS\n" unless(@ARGV);for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g}; print eval(join('',@ARGV)),$/; It handles square roots, power, modulus: pc 1+2 (1 plus 2) 3 pc 3x4 (3 times 4) 12 pc 5^6 (5 to the power of 6) 15625 pc v 49 ( square root of 49 ) 7 pc 12/3 (12 divided by 3) 4 pc 19%4 (19 modulus 4) 3 (you can string maths together too) pc 10 x 10 x 10 1000 pc 10 + 10 + 10 / 2 25 pc 7 x v49 49 Show Sample Output

    perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;'
    JohnGH · 2009-12-21 21:03:27 2
  • This is a big time saver for me. I often grep source code and need to edit the findings. A single highlight of the mouse and middle mouse click (in gnome terminal) and I'm editing the exact line I just found. The color highlighting helps interpret the data.

    mgc() { grep --exclude=cscope* --color=always -rni $1 . |perl -pi -e 's/:/ +/' |perl -pi -e 's/^(.+)$/vi $1/g' |perl -pi -e 's/:/ /'; }
    stinkerweed999 · 2010-01-26 17:00:01 0
  • Like command #4845, prints score, number of entries, and average score.

    username=bartonski;curl -s$username/json|perl -e 'BEGIN{$s=0;$n=0};END{print "Score: $s\nEntries: $n\nMean: ";printf "%3.2f\n",$s/$n}' -0173 -nae 'foreach $f (@F){if($f =~ /"votes":"(-*\d+)"/){$s += $1; $n++;}}'
    bartonski · 2010-02-16 01:03:29 1
  • Requires Net::Twitter. Just replace the double quoted strings with the appropriate info.

    perl -MNet::Twitter -e '$nt = Net::Twitter->new(traits => [qw/API::REST/], username => "YOUR USERNAME", password => "YOUR PASSWORD"); $ud = $nt->update("YOUR TWEET");'
    dbbolton · 2010-06-16 19:46:05 1
  • **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 Show Sample Output

    diff <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file1) <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file2)
    jemptymethod · 2010-10-06 19:14:42 1
  • If you are in an environment where you don't have the base64 executable or MIME tools available, this can be very handy for salvaging email attachments when the headers are mangled but the encoded document itself is intact.

    perl -MMIME::Base64 -ne 'print decode_base64($_)' < file.txt > out
    dmmst19 · 2010-12-13 23:35:20 0
  • This works by reading in two lines of input, turning each into a list of one-character matches that are sorted and compared.

    (echo foobar; echo farboo) | perl -E 'say[sort<>=~/./g]~~[sort<>=~/./g]?"anagram":"not anagram"'
    doherty · 2011-02-17 02:15:46 0
  • This is a naive way of finding source code comments in source code files that use C-like comments: // and /*...*/

    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
    doherty · 2011-07-08 00:17:27 1

  • 2
    route -n | perl -ne '$ANY=""; /^$ANY/ and split /\s+/ and print "Gateway to the World: ",($_[1]!=$ANY)?$_[1]:(`ip address show $_[$#_]`=~/peer ([0-9\.]+)/ and $1),", via $_[$#_].\n"'
    bandie91 · 2011-09-13 08:05:58 0

  • 2
    perl -le 'print$_%3?$_%5?$_:"Buzz":$_%5?"Fizz":"FizzBuzz"for 1..100'
    depesz · 2012-01-10 13:10:30 2
  • - excel date compatible with a separate hour field - added a fixed 1 for easier request counter aggregation - split URL in directory, filename, fileext, query - used with tomcat valve with response bytes replaced by elapsed time Show Sample Output

    #(see sample) $ cat x | perl -pe 'BEGIN{ print "TIME;...\n"; } s!(\S+) - (\S+) - \[(\d\d)/(\S\S\S)/(\S+):(\d\d):(\d\d:\d\d) \S+\] "(\S+) (.*/)(\S+)(?:\.([^?]*)(\?\S*)?) HTTP/\S+" (\d+) (\S+)!$3-$4-$5 $6:$7;$6;$2;$1;$8;$13;1;$14;$11;$10;$9;$12;!' > x.csv
    hute37 · 2012-02-10 16:58:50 0
  • Nasty perl one-liner that provides a sparkline of ping times. If you want a different history than the last 30, just put that value in. It (ab)uses unicode to draw the bars, inspired by . It's not the most bug-free piece of code, but what it lacks in robustness it makes up for in capability. :) If anyone has any ideas on how to make it more compact or better, I'd love to hear them. I included a ping to google in the command just as an example (and burned up 10 chars doing it!). You should use it with: $ ping | $SPARKLINE_PING_COMMAND Show Sample Output

    ping|perl -ne'$|=/e=(\S+)/||next;([email protected]_,$1)>30&&[email protected]_;print"\r",(map{"\xe2\x96".chr(128+7*$_/(sort{$b<=>$a}@_)[0])." "}@_),"$1ms"'
    bartgrantham · 2012-07-06 22:42:06 0
  • ‹ First  < 2 3 4 5 6 >  Last ›

What's this? 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

Show Apt/Dpkg configuration
Shows all configurations to apt and dpkg, rarely changed, you probably still have the default configuration. Go ahead and explore your configuration if you dare, perhaps change your apt-cache directory, Dir::Cache "var/cache/apt/"; or the names of the log files.

This is regarding the command 8263 using an alias to fill in command line options for psql. You can actually just type 'psql'. In order for that to work, you want to set environment variables PGDATABASE, PGHOST, PGUSER, and (except you're using the default) PGPORT. Also, you can add a line "host:port:dbname:user:password" (asterisk ok in some columns) to your ~/.pgpass file. Finally, if you don't like the aligned columns, you can add the line "\pset format unaligned" to your ~/.psqlrc file.

Count items in JSON array
Pipe any JSON to jq, then count with the appropiate expression and use the | length on the array

List files with full path
Prints contents of current directory with the full path prepended to each entry. You can add '-type f' if you don't want the directories to show up (for those less familiar with find). I can't believe ls doesn't have an option for this.

Get AWS temporary credentials ready to export based on a MFA virtual appliance
You might want to secure your AWS operations requiring to use a MFA token. But then to use API or tools, you need to pass credentials generated with a MFA token. This commands asks you for the MFA code and retrieves these credentials using AWS Cli. To print the exports, you can use: `awk '{ print "export AWS_ACCESS_KEY_ID=\"" $1 "\"\n" "export AWS_SECRET_ACCESS_KEY=\"" $2 "\"\n" "export AWS_SESSION_TOKEN=\"" $3 "\"" }'` You must adapt the command line to include: * $MFA_IDis ARN of the virtual MFA or serial number of the physical one * TTL for the credentials

Block known dirty hosts from reaching your machine
Blacklisted is a compiled list of all known dirty hosts (botnets, spammers, bruteforcers, etc.) which is updated on an hourly basis. This command will get the list and create the rules for you, if you want them automatically blocked, append |sh to the end of the command line. It's a more practical solution to block all and allow in specifics however, there are many who don't or can't do this which is where this script will come in handy. For those using ipfw, a quick fix would be {print "add deny ip from "$1" to any}. Posted in the sample output are the top two entries. Be advised the blacklisted file itself filters out RFC1918 addresses (10.x.x.x, 172.16-31.x.x, 192.168.x.x) however, it is advisable you check/parse the list before you implement the rules

diff current vi buffer edits against original file

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.

[vim] Clear a file in three characters (plus enter)
% selects every line in the file. 'd' deletes what's selected. It's a pretty simple combination.

tcpdump from src to dst
then open with wireshark

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.


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: