Difference between revisions of "Perl-regex"
From Bashlinux
(Redirected page to Regular expressions with Perl) |
|||
(5 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
+ | #REDIRECT [[Regular_expressions_with_Perl]] |
||
− | __NOTOC__ |
||
− | = Perl Regex = |
||
− | == Search and replace a word or phrase == |
||
− | * '''All matches''' |
||
− | |||
− | <pre><nowiki> |
||
− | perl -pi -e 's/old string/new string/g' /path/to/the/file |
||
− | </nowiki></pre> |
||
− | |||
− | 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''' |
||
− | |||
− | <pre><nowiki> |
||
− | perl -pi -e 's/old string/new string/ if m/my unique string/' /path/to/the/file |
||
− | </nowiki></pre> |
||
− | |||
− | 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''' |
||
− | |||
− | <pre><nowiki> |
||
− | sed -ie s%old string%$BASH_VARIABLE% /path/to/the/file |
||
− | </nowiki></pre> |
||
− | |||
− | In order to get this done is convenient to use `sed` instead `perl` command. |
||
− | |||
− | == Remove/replace a whole line == |
||
− | |||
− | * '''Conditional match''' |
||
− | |||
− | <pre><nowiki> |
||
− | perl -pi -e '$_="" if m/my unique string/' /path/to/the/file |
||
− | </nowiki></pre> |
||
− | |||
− | This command line removes all the lines that matches ''my unique string'' |
Latest revision as of 23:55, 6 June 2015
Redirect to: