sed and perl Snippets

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
  • -i means update and save directly to input.txt
  • -p means loop over input file(s)
  • -0 means use null record
  • -e means 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
  • -r no need to escape \(.
  • ([^ ]+) grouped, 1 or more excluding space.
  • \1 and \2 reference (…) groups.