perl
Find and Replace (multiline)
Replace \n newlines with real characters \n.
Input
Alice
Bob
Carl
Command
perl -i -p0e "s/\n/\\\\n/g" input.txt
Output
Alice\nBob\nCarl
Notes
perl -i -p -0 -e "s/\n/\\\\n/g" input.txt
-
-imeans update and save directly toinput.txt -
-pmeans loop over input file(s) -
-0means use null record -
-emeans run the one line program"s/…"
sed
Find and Replace
Delete the string
defined('SYSPATH') or die('No direct script access.');
from all *.php files in the ./classes directory recursively.
for FILE in $(find ./classes -name *.php); do \
gsed -i "s/defined('SYSPATH') or die('No direct script access.');//g" $FILE ; \
done;
Insert
Insert the string namespace Sidekicker; on line 2 of all *.php files in the ./classes directory, non-recursively.
for FILE in $(find ./classes -name *.php -maxdepth 1); do \
gsed -i '2inamespace Sidekicker;' $FILE; \
done;
Delete a line
Offending ECDSA key in /Users/user/.ssh/known_hosts:37
I need to delete a line in known_hosts because the host key has changed.
gsed -i "37d" /Users/user/.ssh/known_hosts
Sed regex reference groups
Input
Alice plays the guitar
Bob plays the drums
Command
gsed -r "s/^([^ ]+) plays the ([^ ]+)$/\1 loves \2/"
Output
Alice loves guitar
Bob loves bass
-
-rno need to escape\(. -
([^ ]+)grouped, 1 or more excluding space. -
\1and\2reference(…)groups.