Thursday, November 29, 2007

Selective text replacement in a file on Unix

Select parts of a file for changing by naming a range of lines either by number (e.g., lines 1-20), by RE (between the words "foo" and "bar"), or by some combination of the two. For multiple changes, put the substitution command between braces {...}.


# replace only between lines 1 and 20
1,20 s/Johnson/White/g

# replace everywhere EXCEPT between lines 1 and 20
1,20 !s/Johnson/White/g

# replace only between words "foo" and "bar"
/foo/,/bar/ { s/Johnson/White/g; s/Smith/Wesson/g; }

# replace only from the words "ENDNOTES:" to the end of file
/ENDNOTES:/,$ { s/Schaff/Herzog/g; s/Kraft/Ebbing/g; }

No comments: