2

Please do pardon me if my question sounds a bit awkward. I am looking for a regex which will replace line numbers in perl source file without affecting values assigned to scalars.

I think below will make my question a little bit clearer. Say I have a perl source which looks like this:

1. $foo = 2.4;
2. print $foo;

I would like a regular expression to replace those line numbers (1. 2. etc..) without affecting value assigned to scalars, and so in this case $foo.

Thanks

2
  • it sounds like a basic question, did you search ? Commented Feb 23, 2012 at 10:08
  • Well, what is the difference between a line number and an scalar assignation? If you say "line numbers always are at the start of a line, and scalar assignations are not", then the regexp becomes quite easy.. s/^\d//; will remove all numbers only at the start of a line. Commented Feb 23, 2012 at 10:09

2 Answers 2

5

anchor your regexp to the start of the line:

to remove the numbers:

perl -p -i.bak -e's{^\d+\. }{}' myperl
Sign up to request clarification or add additional context in comments.

Comments

4

Within a perl regex you can use the caret symbol ^ to represent the start of a line. $ represents the end of a line. These are known as anchors.

So to find a number \d at the beginning of a line (only) you can search for

/^\d+/

If you wanted to remove those numbers you can "replace" them with nothing, as in

s/^\d+//g

You also want to include the dot after the number, so you might try ;

/^\d+./

But in regex a dot represents "any character" so you will need to escape the dot to have it interpreted literally

/^\d+\./

The caret symbol ^ also serves double-duty in character sets (it negates them), I only mention this as it is a common source of confusion when learning regex.

/[^\d]/   # Match characters that are not digits

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.