Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'Three Tips' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Three Tips
Authored by: sharumpe on Feb 27, '02 12:57:24PM
Heya, this is something I do ALL the time - glad that someone thought about submitting it.

I have a couple tips for doing this, though:
1) If you think you would like to keep a backup of the file(s) that you are doing this to, you can put an extension after the 'i' option, like this:
perl -pi.bak -e 's/foo/bar/g' filename

This will rename the original file to filename.bak before doing the search/replace.

2) You can search case-insensitively with 's/foo/bar/gi'

3) You can change the line endings to Unix style like this:
perl -pi -e 's/r//g' filename


Mr. Sharumpe

[ Reply to This | # ]
careful ...
Authored by: Djonli on Feb 27, '02 11:49:32PM

From examples shown above, it will replace all words containing "foo" with "...bar...". For example, "fool" --> "barl", etc. To change word "foo" to "bar", use the following syntax for the regular expression:

s/\bfoo/bar/g # Note the "\b"

use "s/\bfoo/bar/gi" for case-insensitive replacement.



[ Reply to This | # ]
careful ...
Authored by: pmccann on Feb 28, '02 01:52:53AM

Hey Rob, will the new geeklog stop robbing code fragments of their backslashes? Both parent and grandparent of this post have lost such symbols, rendering the code somewhat silly!

In the grandparent it should be "backslash r" I presume, though I should note that this runs into **exactly** the problem that my first (and, ahem, second) post was intended to warn against. If the file is big you're doing a **lot** of heavy lifting that can easily be avoided. In fact, I really don't think that prescription for changing line endings works at all (unless you've only got one line in the file!). The problem is that the whole file is **one line** to perl, so it reads it in, eliminates the CR's in the line, and then prints out the single line as requested (with an LF on the end). Not what you're after.

You really want something like

perl -pi -e 'tr/



[ Reply to This | # ]
careful ...
Authored by: pmccann on Mar 01, '02 12:49:56AM

I surrender!

geeklog wins... (another victim of the backslash in the same post as this problem was being described). Let's try again: I'll use % where there should be a backslash in two places in the following line.

perl -pi -e 'tr/%015/%012/' filename

Now let me out of here!

Cheers,
Paul (anyone else want a forum they want littered with nonsense?)



[ Reply to This | # ]
careful ...
Authored by: Djonli on Mar 02, '02 05:23:07AM

Hmm .. The preview showed the "<back slash>b", but I can see that my post lost the <backslash>.

So, for those people that are new to regular expression, please add the <back slash> in front of the "b".



[ Reply to This | # ]