Regex

Some usefull example regex instructions using perl instead of awk/sed:


repeatedly replace ‘cat’ with ‘dog’ in file ‘filename.txt’ after making a backup file ‘filename.txt.old’:

perl -i.old -p -e 's/cat/dog/g' ./filename.txt


replace in single lines from stream:

$ echo -e "111\n222\n333" | perl -pe 's/\d(.*)/[ $1 ]/'
[ 11 ]
[ 22 ]
[ 33 ]


replace in multiple lines from stream:

$ echo -e "111\n222\n333" | perl -0pe 's/1(.*)3/[ $1 ]/s'
[ 11
222
33 ]


repeatedly extract from multiple lines from stream:

$ echo -e "1aaaa\naaa2bb1cccc\nccc2dd" | perl -0ne 'while (/1(.*?)2/sg) {print "[ $1 ]\n"}'
[ 
aaaa
aaa ]
[ 
cccc
ccc ]

repeatedly extract from ‘begin’ until matching ‘end’ using counter over multiple lines:

echo -e "begin\n  1\n  begin\n    2\n  end\n  3\nend\n4\nend" | perl -0ne 'while (/(begin(?{$c=1})(?(?{$c>0})(?:begin(?{$c++})|end(?{$c--})|.))*)/sg) {print "[ $1 ]\n"}'
[ begin
  1
  begin
    2
  end
  3
end ]