2012-10-30

How to substutitute characters in all files of a directory using regex and perl

perl -i -pe 's/CharacterToSubstiture/SubstituteWithThis/g' myfilename

Example:
Imagine I have got these two files:

shopping_list_groceries.txt:
- 2 apples
- 3 red paprika

shopping_list_clothes.txt:
- 2 pairs of socks
- 1 red t-shirt

And now I decide to not like red any more, but to prefer green:

perl -i -pe 's/red/green/g' shopping_list*txt


The text files now look like this:
shopping_list_groceries.txt:
- 2 apples
- 3 green paprika

shopping_list_clothes.txt:
- 2 pairs of socks
- 1 green t-shirt


What does the one-liner do?
perl # use perl :)
-i # change in the file, if you skip this part, the changes will be printed to stdout
-pe # I don't know
's/red/green/g' # RegEx: 
                 's # Substitute...
                 /red # ...every occurence of the string "red"...
                 /green # ...with the string "green"...
                 /g' # ... everywhere ...
shopping_list*.txt # ...in all files starting with 'shopping_list' and ending with '.txt



No comments:

Post a Comment