tags:

views:

127

answers:

4

I need to escape \n so on output I really get newline or tab

$ perl -p -e 's/e/a/ge'

now I want each e to be substituted with \n

$ perl -p -e 's/e/\n/ge'

but even \n gives me an error.

this was a simplified example. In real script(makefile) I have

substitute := perl -p -e 's/@([^@]+)@/defined $$ENV{$$1} ? $$ENV{$$1} : $$1/ge'

and in target I have such a nice command

$(substitute) $< > $@

and if the input file for perl contains \n at output I will see it literally... I want to have real newline.

+2  A: 

Remove the e modifier and the substitution will work fine:

perl -p -e 's/e/\n/g' file

From perldoc perlop:

e   Evaluate the right side as an expression.

UPD: If you want to preserve it, put the escape sequence in double quotes:

perl -p -e 's/e/"\n"/ge' file
eugene y
guess I need it, because of this in real case `perl -p -e 's/@([^@]+)@/defined $$ENV{$$1} ? $$ENV{$$1} : $$1/ge'`. And this thing goes to makefile... the real world is too complicated ^^
Michael
@Michael -- where's the `\n` or `\t` in there?
Joe
@Joe: I've updated my original post. Sorry guys I thought things are simple... looks not.
Michael
@eugene y: didn't work, can see "\n" in output. The string from the variable passed to replacement part is like this `em:updateURL="http://bla/update.rdf""\n"` (the last one per your recommendation.
Michael
@Michael: you need an extra e along with the quotes; see my answer
ysth
@ysth: extra `e` didn't help, sorry
Michael
@Michael: what *did* happen? Can you show a snipped down makefile and tell us what the output of make -n should be?
ysth
+2  A: 

You don't really need e in your regexp:

dpavlin@llin:~/private/home_html$ perl -p -e 's/e/\n/g'
foedoe
fo
do
dpavlin
+2  A: 

To interpolate things that themselves need interpolation (like variables or escapes), use a double e and add quotes:

perl -p -e 's/@([^@]+)@/q!"! . ( defined $ENV{$1} ? $ENV{$1} : $1 ) . q!"!/gee'

That won't work if the substitution itself contains an unescaped " or $ or @; in that case, you'll need to do the backslash-escape handling separately.

ysth
A: 
echo xeieio | perl -pe 's/(.)/$k=$1;$k=~s#e#\n#;$k/ge'

outputs:

x
i
io

What it does... for each character, assign it to $k, run a simple s/e/\n/ on $k, then print $k. (Also, as always, there's more than one way to do it)

Kyle