Perl-regex: Difference between revisions

From Bashlinux
Jump to navigationJump to search
Content deleted Content added
Manpaz (talk | contribs)
No edit summary
 
Manpaz (talk | contribs)
No edit summary
Line 8: Line 8:
</nowiki></pre>
</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.
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'''
* '''Conditional match'''
Line 16: Line 16:
</nowiki></pre>
</nowiki></pre>


This command line search only for the lines that matches ''my unique string'' and then replaces ''old string'' with ''new string''
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'''
* '''Search and replace using bash shell variables'''
Line 24: Line 24:
</nowiki></pre>
</nowiki></pre>


In order to get this done is convenient to use `sed` instead `perl` command.
In order to get this done is convenient to use `sed` instead `perl` command.


== Remove/replace a whole line ==
== Remove/replace a whole line ==
Line 34: Line 34:
</nowiki></pre>
</nowiki></pre>


This command line removes all the lines that matches ''my unique string''
This command line removes all the lines that matches ''my unique string''

Revision as of 09:21, 3 February 2010

Perl Regex

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 -ie s%old string%$BASH_VARIABLE% /path/to/the/file
 
In order to get this done is convenient to use `sed` instead `perl` command.

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