This article is part of the article series "Perl One-Liners Explained."
<- previous article next article ->
Perl One Liners

Hi all! I am starting yet another article series here. Remember my two articles on Awk One-Liners Explained and Sed One-Liners Explained? They have received more than 150,000 views total and they attract a few thousand new visitors every week. Inspired by their success, I am going to create my own perl1line.txt file and explain every single oneliner in it. I hope it becomes as as awk1line.txt and sed1line.txt files.

A tiny intro to those unfamiliar with the awk1line.txt and sed1line.txt files -- they contain around 80 useful awk and sed one-liners for doing various text file manipulations. Some examples are double spacing a file, numbering the lines, doing various text substitutions, etc. They were compiled by Eric Pement. Kudos to him!

The article will be divided in seven parts or more parts. In parts 1 - 6 I will create the one-liners and explain them, and in the last part I will release the perl1line.txt file. I found that splitting the article in many parts is much easier to get it written, that's why I do it.

Here is the general plan:

The one-liners will make heavy use of Perl special variables. Luckily, a few years ago I compiled all the Perl special vars in a single file and called it Perl special variable cheat-sheet. Even tho it's mostly copied out of perldoc perlvar, it's still handy to have in front of you. I suggest that you print it.

Awesome news: I have written an e-book based on this article series. Check it out:

Other than that, I can't wait to start writing the article, so here I go:

File Spacing

1. Double space a file.

perl -pe '$\="\n"'

This one-liner double spaces a file. There are three things to explain in this one-liner. The "-p" and "-e" command line options, and the "$\" variable.

First let's start with the "-e" option. The "-e" option can be used to enter a Perl program directly in the command line. Typically you don't want to create source files for every small program. By using "-e" you can handily specify the program to execute on the command line.

Next the "-p" switch. Specifying "-p" to a Perl program causes it to assume the following loop around your program:

while (<>) {
    # your program goes here
} continue {
    print or die "-p failed: $!\n";

This construct loops over all the input, executes your code and prints the value of "$_". This way you can effectively modify all or some lines of input. The "$_" variable can be explained as an anonymous variable that gets filled with the good stuff.

The "$\" variable is similar to ORS in Awk. It gets appended after every "print" operation. Without any arguments "print" prints the contents of "$_" (the good stuff).

In this one-liner the code specified by "-e" is '$\="\n"', thus the whole program looks like this:

while (<>) {
    $\ = "\n";
} continue {
    print or die "-p failed: $!\n";

What happens is that after reading each line, "$_" gets filled with it (including the existing line's newline), the "$\" gets set to a newline itself and "print" is called. As I already mentioned, without any arguments "print" prints the contents of "$_" and "$\" gets appended at the end. The result is that each line gets printed unmodified and it's followed by the "$\" which has been set to newline. The input has been double-spaced.

There is actually no need to set "$\" to newline on each line. It was just the shortest possible one-liner that double-spaced the file. Here are several others that do the same:

perl -pe 'BEGIN { $\="\n" }'

This one sets the "$\" to newline just once before Perl does anything (BEGIN block gets executed before everything else).

perl -pe '$_ .= "\n"'

This one-liner is equivalent to:

while (<>) {
    $_ = $_ . "\n"
} continue {
    print or die "-p failed: $!\n";

It appends another new-line at the end of each line, then prints it out.

The cleanest and coolest way to do it is probably use the substitution "s///" operator:

perl -pe 's/$/\n/'

It replaces the regular expression "$" that matches at the end of line with a newline, effectively adding a newline at the end.

2. Double space a file, except the blank lines.

perl -pe '$_ .= "\n" unless /^$/'

This one-liner double spaces all lines that are not completely empty. It does it by appending a newline character at the end of each line that is not blank. The "unless" means "if not". And "unless /^$/" means "if not 'beginning is end of line'". The condition "beginning is end of line" is true only for lines that contain the newline character.

Here is how it looks when expanded:

while (<>) {
    if ($_ !~ /^$/) {
        $_ .= "\n"
} continue {
    print or die "-p failed: $!\n";

A better test that takes spaces and tabs on the line into account is this one:

perl -pe '$_ .= "\n" if /\S/'

Here the line is matched against "\S". "\S" is a regular expression that is the inverse of "\s". The inverse of "\s" is any non-whitespace character. The result is that every line that has at least one non-whitespace character (tab, vertical tab, space, etc) gets double spaced.

3. Triple space a file.

perl -pe '$\="\n\n"'


perl -pe '$_.="\n\n"'

They are the same as one-liner #1, except that two new-lines get appended after each line.

4. N-space a file.

perl -pe '$_.="\n"x7'

This one-liner uses inserts 7 new lines after each line. Notice how I used '"\n" x 7' to repeat the newline char 7 times. The "x" operator repeats the thing on the left N times.

For example:

perl -e 'print "foo"x5'

would print "foofoofoofoofoo".

5. Add a blank line before every line.

perl -pe 's//\n/'

This one-liner uses the "s/pattern/replacement/" operator. It substitutes the first pattern (regular expression) in the "$_" variable with the replacement. In this one-liner the pattern is empty, meaning it matches any position between chars (and in this case it's the position before first char) and replaces it with "\n". The effect is that a newline char gets inserted before the line.

6. Remove all blank lines.

perl -ne 'print unless /^$/'

This one-liner uses "-n" flag. The "-n" flag causes Perl to assume to following loop around your program:

while (<>) {
    # your program goes here

What happens here is that each line gets read by the diamond "<>" operator and is placed in the dolar underscore special variable "$_". At this moment you are free to do with it whatever you want. You specify that in your main program text.

In this one-liner the main program is "print unless /^$/", it gets inserted in the while loop above and the whole Perl program becomes:

while (<>) {
    print unless /^$/

Unraveling it further:

while (<>) {
    print $_ unless $_ =~ /^$/

This one-liner prints all non-blank lines.

A few other ways to do the same:

perl -lne 'print if length'

This one uses the "-l" command line argument. The "-l" automatically chomps the input line (basically gets rid of newline at the end). Next the line is tested for its length. If there are any chars left, it evals to true and the line gets printed.

perl -ne 'print if /\S/'

This one-liner behaves differently than the "print unless /^$/" one-liner. The "print unless /^$/" one-liner prints lines with spaces and tabs, this one doesn't.

7. Remove all consecutive blank lines, leaving just one.

perl -00 -pe ''

Ok, this is really tricky, ain't it? First of all it does not have any code, the -e is empty. Next it has a silly -00 command line option. This command line option turns paragraph slurp mode on. A paragraph is text between two newlines. All the other newlines get ignored. The paragraph gets put in "$_" and the "-p" option prints it out.

Later I found a shorter version of this one-liner:

perl -00pe0

8. Compress/expand all blank lines into N consecutive ones.

perl -00 -pe '$_.="\n"x4'

This one-liner combines the previous one and one-liner #4. It slurps lines paragraph wise, then appends (N-1) new-line. This one-liner expands (or compresses) all new-lines to 5 ("\n" x 4 prints four, and there was one at the end of paragraph itself, so 5).

Perl one-liners explained e-book

I've now written the "Perl One-Liners Explained" e-book based on this article series. I went through all the one-liners, improved explanations, fixed mistakes and typos, added a bunch of new one-liners, added an introduction to Perl one-liners and a new chapter on Perl's special variables. Please take a look:

Have Fun!

Have fun with these file spacing one-liners. The next part is going to be about line numbering and calculations one-liners.

Can you think of other file spacing operations that I did not include here?

This article is part of the article series "Perl One-Liners Explained."
<- previous article next article ->


Programmer Permalink
February 25, 2009, 13:46

So your goal is to have a page of one-liners in really obscure, unreadable languages... why? Why not just let obsolete languages die?

Fred Permalink
July 15, 2010, 19:10

Obsolete?!? Are chain-saws obsolete?

December 30, 2011, 14:44

I'm seeing this post in 2012 (ok, 30/Dec/2011); and let me tell you; Perl is nowhere near obsolete, I work with ERP and database software that has absolutely nothing to do with Perl. The only reason I even know Perl is because (when it was the major CGI option) I made websites and wanted to learn a CGI language.
Today my use of perl is pretty much restricted to one-liners (and occasional multi-line scripts) to correct, replace and append text to my SQL scripts and procs.
And I do so very, very frequently. There currently is NOTHING, not one program or language available (and I have looked) that can replace perl scripts to do these things. Not that there aren't any programs that can do the same thing, they can; but they're clumsy, unstable, require much more work on my part than a simple perl script and they are always incomplete (they do ALMOST exactly what you need, with perl scripts you make it do EXACTLY what you need).
I've yet to find anything more powerful for batch file processing than a perl shell; and as a Windows user, I recommend strawberry perl portable; I can take it to all my clients and impress everyone with how quickly I can fix all the scripts that need simple changes.

Perl strings has always been something that put question marks and "WTF"s on programmers' heads (even experienced perl programmers). But anyone who's worked with them, misses having them in other languages; a single line that doesn't seem to make any sense can be so damn powerful and replace so many lines of code you wouldn't believe.

xer0.5ive Permalink
September 14, 2018, 07:57

2018 and it's still true.

ohlolsyswritenow Permalink
November 26, 2013, 12:19

I bet you use python, c# and vbscript. i don't like you at all.

ARealProgrammer Permalink
August 07, 2014, 12:18

It is sad when people who are failures try and pull others down.

I wonder why Programmer was reading the page, don't you?

Programmer, some friendly advice: get therapy! Your attempts to pull others down to where you see yourself only hurt you and keep your self-esteem where it is, in the gutter.

Look for the good, and you will find it. Look for the bad, and you will find it

February 25, 2009, 14:41

I just bought the first item on your list, PCM, but to myself :-)

February 25, 2009, 15:13

Ali, could have bought two - one for me and one for you! :) I now have to put it back in wishlist. :(

Anno (icke on freenode #perl) Permalink
February 25, 2009, 17:32

Personally, I wouldn't give Perl one-liners the promotion and attention
you are giving them.

That aside, it's written in a readable, relaxed style. (Good English too,
from one second-language speaker to another.) I haven't checked every
technical detail, I'll trust you to get that right.

The subject "File Spacing" is less than clear, it doesn't tell me what to expect. Even the term "double spacing" isn't quite definite, besides your meaning it also used for the practice of following the period after each sentence with two blanks.

Also, the subject is awfully narrow. If you go on at this pace it'll take dozens of articles to cover the full range of one-liners. How about extending the scope to "Whitespace Handling"? Add one-liners for, say, tab expansion, space-normalization (multiple blanks/tabs become one), word counting, you'll think of more. That would give it a clearer subject and let it cover more ground.


Kroak Permalink
February 25, 2009, 17:38

Hey Petris, just to know, English is your mother tongue ?

Roman Permalink
February 25, 2009, 18:02

Unfortunately, "perl -ne 'print if chomp and length'" strips newlines before printing, so the result is a wall of text. I suggest:

perl -lne 'print if length'


February 25, 2009, 20:03

oops, i didn't realize i removed it from your list by browsing it from there. sorry for that.

February 25, 2009, 21:32

I think it's stupid to say perl (or even awk) is obsolete. The language does its job, and does it fine. It may have limited applicability thou

ohlolsyswritenow Permalink
November 26, 2013, 12:17

it has unlimitited 'applicability'. ape.

dave Permalink
February 25, 2009, 21:35

I miss Perl, especially the multitude of techniques for achieving the same end result. These days I am writing Java, reminding my peers how verbose it all is. One-liners may have their drawbacks, but this kind of content is interesting to read and enlightening at the same time. Thank you.

February 26, 2009, 02:42

I got one character better at double spacing a file!

perl -pe "s,,\n,"

February 26, 2009, 09:42

Roman, you're a very sharp guy, always catch all the bugs. Thanks! I am now fixing that mistake.

Anno, thank you for your review. I will not go at this pace, and your mentioned space normalization and tab expansion will be covered in "text conversion and substitution" article.

Kroak, nope, English is not my mother tongue. I am just very passionate about English.

Jake, ehehehe. Your one-liner prints newline before the line. I'll include it in my list! :)

rveri Permalink
April 25, 2010, 13:05

What about this one: for double spacing: Easy and Cool!!

# perl -pe 's/\n/\n\n/' file


yifang Permalink
September 18, 2012, 20:39

What if there is a double space line already?

February 26, 2009, 17:26


I enjoyed it, and learned a few new things.

Roman Permalink
February 27, 2009, 17:59


You didn't describe the effects of -l fully, though. Not only it makes Perl chomp every line, it also sets $\ to (in this case) $/, so you don't get a wall of text.

Amir Karger Permalink
March 03, 2009, 19:08

Plug alert!
Check out the Scriptome, a set of one-liners for doing data munging. It's aimed at biologists but most of the scripts are more generic. Stuff like merging or filtering tab-delimited data. Browse to a tool and click on the "Expand code" button to make the one-liner more readable.

nwe Permalink
October 19, 2009, 15:32

Good i like it Permalink
January 08, 2010, 01:53

hi peter

In this article I saw this one-liner "perl -00pe0". I just got confused with the 0 in the end of the one-liner.

Could you tell me sth about it? Is there any documents about it?

Thx ^_^

January 08, 2010, 02:04, good question.

This one-liner does not need any code to run. -p argument generates all the necessary code already.

But to run a one-liner we actually need to specify something to -e argument.

At first I specified the empty string:

perl -00 -p -e ''

But then I discovered that the empty string can be replaced just by a 0 (because 0 does nothing):

perl -00 -p -e 0

You could as well have used any constant:

perl -00 -p -e 1

You just need to specify something to -e that does nothing, to satisfy the interpreter argument checking. Permalink
January 08, 2010, 02:43

Thank you so much. I was just wondering why it is 0 a moment ago. Now I know the -e needs nothing but a constant here.

BTW: It's 2am now, you are always working so late? I am form China, it's 11:00 am here ^_^

James Zhu Permalink
September 24, 2012, 02:05


January 08, 2010, 03:00, I am happy that you understood it now. ^_^

It's 5am here actually. I am working at nights, and sometimes during day. Depends on when I woke up!

lucia Permalink
February 11, 2010, 08:47

Thanks for your sharing .
When did you write summary during your studying or after you reading the book so mang times?
I ask this because your writing so logical.When I finish one chapter, I still cannot give just a globe logical for the whole book.
I mean this:
Here is the general plan:

Part I: File spacing.
Part II: Line Numbering.
Part III: Calculations.
Part IV: String creation. Array creation.
Part V: Text conversion and substitution.
Part VI: Selective printing and deleting of certain lines.
Part VII: Release of perl1line.txt.

How do you make your plan when first started.I'm lack of this skill, can you give me a suggest in improving this skill. Thanks so much!

February 11, 2010, 18:18

Lucia, my suggestion is to reuse knowledge. I reused the plan from awk one-liners explained and sed one-liners explained articles. So it was pretty easy.

rveri Permalink
April 25, 2010, 13:19


Great perl codes..Enjoyed.

rob Permalink
March 29, 2011, 21:00

Useful! Looking forward to the e-book.

Balraj Permalink
May 14, 2011, 07:23

Your one line perl article is very good and keep continue for all perl users.

Thanks & Regards,

Ian Permalink
October 17, 2011, 04:37

Thanks for this article series.

Perl is a powerful and practical language, and is very useful for a huge array of tasks. There are many cases where one-liners are the best way to accomplish a task, particularly text processing.

Michael Permalink
December 02, 2011, 19:15

Thanks Peter,

A different use of markers for the beginning and end of line are backslash A and backslash Z \A\Z.
I also like to use perl one liners inside a VI session like this : % ! perl -pe 's/foo/bar/'
The : inside VI puts the editor into command line mode, the % says for every line in the file, the ! says run the following in the shell. The perl program runs on every line making the edit.

ohlolsyswritenow Permalink
November 26, 2013, 11:51

To 'Programmer', first comment:
it's not obsolete you chimp. go hug a python book and catch the exceptions. there is no 'next-generation' language after perl, it still does what people need. you want to revise the universal rules that govern logic? build a time machine and travel back to before you were conceived, then make your mother stop wanting a baby, THEN REVISE LOGIC. iẗ́'s a plan. goddamnit, i love perl. rock and roll!

ohlolsyswritenow Permalink
November 26, 2013, 12:14

what the heck is this article about anyway? it's no substitute for perldoc.
$ perldoc perldoc

Vrindavan Singh Yadav Permalink
September 02, 2016, 11:58

Hi Peter Krumins,

Thank you very much for your articles on Perl. I'm new to Perl and was searching for a basic tutorial. God know how I reached here, but after reading your articles I did get clear picture of Perl, especially the regex.

Leave a new comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "linux_127": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.