GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

Reputation: 8920

Why is my carriage return not working in my perl script?

Stepping into perl from sed I am trying to practice on a CSS file but I'm having issues and I am not finding what the issue could be from multiple searches. In my bash script I am targeting a CSS file that has:

.thisclass
{   font-family: "Times New Roman";
    line-height: 1.20em;
    font-size: 1.00em;
    margin: .25em 0;
    color: rgb(0,0,0);
}

and my goal is:

.thisclass {    
    font-family: "Times New Roman";
    line-height: 1.20em;
    font-size: 1.00em;
    margin: .25em 0;
    color: rgb(0,0,0);
}

The perl I tried is perl -pe 's:\r^{: {\r:g' but it doesn't work. If I try:

perl -pe 's:^{:foobar:g'

the output is:

.thisclass
foobar  font-family: "Times New Roman";
    line-height: 1.20em;
    font-size: 1.00em;
    margin: .25em 0;
    color: rgb(0,0,0);
}

If I try perl -pe 's:\r:foobar:g' the entire document gets modified with foobar

In my text editor I can do \r^{ and in my terminal I can do s/\n{/ {\n/g; but I cannot get a carriage return or a new line to work in perl executed through a script with sh foo.sh. I have tried using \s (Whitespace character equivalent to [\t\n\r\f]) but with no success.

So why is the carriage return not working in my perl? Is there a better way to execute what I am looking to do? If there is a better way can you explain why, please.

Upvotes: 1

Views: 608

Answers (1)

Jim Davis
Jim Davis

Reputation: 5290

You're reading the file line-by-line, so each line ends with the carriage return or newline -- there's nothing after it. \r{ doesn't appear on any single line.

You can use the -0777 switch to enable slurp mode and read the whole file as a string:

perl -0777 -pe 's/\R{/ {\n /g' foo.css

The \R should match any type of newline, be it \r\n, \r, or \n.

Upvotes: 3

Related Questions