3 ms·
I use perl one-liners, thanks to the power of -n, -i and -p switches. perl -n -e <expression> <file> runs the expression on each and every line of <file> (c
by wazoox 12y ago
I use perl one-liners, thanks to the power of -n, -i and -p switches.
perl -n -e <expression> <file>
runs the expression on each and every line of <file> (can be STDIN of course).
perl -p -e <expression> <file>
prints out every line for which the expression returns true.
The -i option allows treating files in place. Add -i<extension> to create a <file>.<extension> backup, just in case.
examples:
perl -p -e '/admin/' file
perl -p -e '^/admin/' file
behaves exactly like the basic awk examples. We can also replace stuff :
perl -p -e 's/admin/bozo/g' file
print all lines matching 'admin', replacing 'admin' with 'bozo'.
Now if you just want to replace all occurrences of 'admin' with 'bozo' in the file:
perl -pi -e 's/admin/bozo/g' file
For instance perl allows you to use a different separator than / for regexps, very useful when manipulating paths:
perl -pi -e 's#/some/path/#/different/path/#g' file
Of course instead of a simple awk/sed substitute, you can run more elaborate code, and even use perl modules in your one liners with the -M switch:
perl -MData::Dumper -n -e 'print Dumper $1 if m/^(admin .w+)/' file
Lastly, perl allows you to use q(string) instead of 'string' and qq(string) instead of "string", that avoids lots of escaping when typing in oneliners, so instead of:
perl -n -e 'print \'found\' if m/admin/' file
Use
perl -n -e 'print q(found) if m/admin/' file