Eikonal Blog

2010.07.13

Command line based text replace

sed

  • sed 's/Mark Monre/Marc Monroe/' 1.txt > 2.txt
  • find ./* -type f -exec sed -i 's///g' {} \;

The “replace” command

  • Syntax:
    replace OLD-STRING NEW-STRING OUTPUT-FILE
  • Example:
    $ replace UNIX Linux  newfile
  • Example:
    $ cat /etc/passwd | replace : '|'
  • Partial support for regular expressions: \^ – matches start of line, and $ matches end of line.
  • Example: replace all IP address 192.168.1.2 start of line:
    $ replace \^192.168.1.2 192.168.5.10  newfile
  • a bash script, ‘fixer.sh’
    #!/bin/bash
    replace CHANGEFROM CHANGETO $1.tmp
    rm $1
    mv $1.tmp $1
    

    now run this command line:

    $ grep CHANGEFROM |cut -d':' -f1 |xargs -n 1 fixer.sh

    the results is that all files in the directory (or whatever you grep for) will be changed automagically.
    just make sure the grep doesn’t include the fixer script itself, or it will die half-way through changing when execute permissions are reset!


Perl


Sources:


Related: Regular expressions – https://eikonal.wordpress.com/2010/04/02/regular-expressions/ | Perl online – https://eikonal.wordpress.com/2010/02/15/perl-online/

4 Comments »

  1. […] Get better at awk/sed/grep – http://kristianrumberg.wordpress.com/2010/09/01/get-better-at-awksedgrep/ Related here: Command line based text replace – https://eikonal.wordpress.com/2010/07/13/command-line-based-text-replace/. […]

    Like

    Pingback by sed tricks « Eikonal Blog — 2010.10.05 @ 15:59

  2. […] Command line based text replace – https://eikonal.wordpress.com/2010/07/13/command-line-based-text-replace/ […]

    Like

    Pingback by Unix pages (at this blog) « Eikonal Blog — 2011.04.04 @ 15:46

  3. […] http://www.regexmagic.com/ Related (here at this blog): Command line based text replace – https://eikonal.wordpress.com/2010/07/13/command-line-based-text-replace/ | Perl online – […]

    Like

    Pingback by Regular expressions « Eikonal Blog — 2011.04.27 @ 09:16

  4. […] | Command line based text replace – https://eikonal.wordpress.com/2010/07/13/command-line-based-text-replace/ Share this:StumbleUponDiggRedditLike this:LikeBe the first to like this post. Comments […]

    Like

    Pingback by Perl online « Eikonal Blog — 2011.08.13 @ 13:09


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: