Difference between revisions of "Perl-regex"
From Bashlinux
(talk) |
|||
Line 1: | Line 1: | ||
__NOTOC__ |
__NOTOC__ |
||
= Perl Regex = |
= Perl Regex = |
||
− | == |
+ | == How to search and replace a word or phrase == |
* '''All matches''' |
* '''All matches''' |
||
Line 27: | Line 27: | ||
Always use `-i -e` instead `-ie`, if not you will end up with another file with the same name but with an `e` at the end of the file name. |
Always use `-i -e` instead `-ie`, if not you will end up with another file with the same name but with an `e` at the end of the file name. |
||
− | == |
+ | == How to remove/replace a whole line == |
* '''Conditional match''' |
* '''Conditional match''' |
||
Line 37: | Line 37: | ||
This command line removes all the lines that matches ''my unique string'' |
This command line removes all the lines that matches ''my unique string'' |
||
+ | == How to work with "sed" command == |
||
− | == Other Regex == |
||
Attached is a file [[[Media:perl-regex$sed1line.txt]]] with a very useful list of sed commands called ''One-Liners for sed''. Updated version is always available at http://sed.sourceforge.net/sed1line.txt |
Attached is a file [[[Media:perl-regex$sed1line.txt]]] with a very useful list of sed commands called ''One-Liners for sed''. Updated version is always available at http://sed.sourceforge.net/sed1line.txt |
Revision as of 15:15, 4 June 2012
Perl Regex
How to search and replace a word or phrase
- All matches
perl -pi -e 's/old string/new string/g' /path/to/the/file
This command line replaces all the instances of old string with new string that are found in `/path/to/the/file`. To replace only the first instance, remove the g at the end of the command.
- Conditional match
perl -pi -e 's/old string/new string/ if m/my unique string/' /path/to/the/file
This command line search only for the lines that matches my unique string and then replaces old string with new string
- Search and replace using bash shell variables
sed -i -e s%old string%$BASH_VARIABLE% /path/to/the/file
In order to get this done is convenient to use `sed` instead `perl` command. Always use `-i -e` instead `-ie`, if not you will end up with another file with the same name but with an `e` at the end of the file name.
How to remove/replace a whole line
- Conditional match
perl -pi -e '$_="" if m/my unique string/' /path/to/the/file
This command line removes all the lines that matches my unique string
How to work with "sed" command
Attached is a file [[[Media:perl-regex$sed1line.txt]]] with a very useful list of sed commands called One-Liners for sed. Updated version is always available at http://sed.sourceforge.net/sed1line.txt