20070702 who says perl isnt a text editor - plembo/onemoretech GitHub Wiki

title: who says perl isn’t a text editor? link: https://onemoretech.wordpress.com/2007/07/02/who-says-perl-isnt-a-text-editor/ author: lembobro description: post_id: 680 created: 2007/07/02 16:12:00 created_gmt: 2007/07/02 16:12:00 comment_status: open post_name: who-says-perl-isnt-a-text-editor status: publish post_type: post

who says perl isn’t a text editor?

This works every, and any, where:

perl -pi -e 's/existing_text/replacing_text/g' filename

You can simply use an asterisk (”*”) in place of “filename” to hit every file in a directory (although I don’t recommend it — 9 times out of 10 you’ll be sorry you did). Using the -pi.bak switch will create a backup of the original file in the process.

When you come across the need to match on forward slashes (such as when you’re search and replacing URL strings), simply escape the each forward slash with a backslash (/).

There’s a good article on this at Cool Computing.

Say you’ve got an LDIF or other file containing blocks of text from which you want to remove a line that shows up inside each block. If you want to remove that particular line and close up the whitespace left over, you’d do something like this:

perl -pi -e 's/^userpassword.+n$//g' file.ldif

In the above example every line beginning with the text “userpassword” is going to get removed, along with the linefeed character at the end of the line, which will make this:

dn: cn=test user,ou=people,dc=example,dc=com
cn: test user
sn:  user
userpassword: {SHA} A10SH3ldiER
givenname: test

look like this:

dn: cn=test user,ou=people,dc=example,dc=com
cn: test user
sn:  user
givenname: test

Pretty neat, eh?

P.S.: If you ever find yourself in need of just stripping blank lines in a file, for example something like:

dn: uid=112345,ou=people,dc=example,dc=com

dn: uid=112346,ou=people,dc=example,dc=com

dn: uid=112347,ou=people,dc=example,dc=com

you can try this little regex:

perl -pi -e 's/^n$//g' filename.ldif

Copyright 2004-2019 Phil Lembo