One Line Command to Find and Replace Text in a File

From ScorecWiki

Jump to: navigation, search
 perl -pi -e 's/find/replace/g' *.txt

For example suppose all instances of libpskernel.a need to be replaced with libpskernel.so in several Makefile.am's:

 > grep "${SIM_PSKRNL_LIB_DIR}/libpskernel" `find . -name Makefile.am`          
 ./test/iGeom/test1/Makefile.am:        ${SIM_PSKRNL_LIB_DIR}/libpskernel.so \
 ./Itaps/common/Makefile.am:            ${SIM_PSKRNL_LIB_DIR}/libpskernel.a \
 ./Itaps/pmesh/Makefile.am:             ${SIM_PSKRNL_LIB_DIR}/libpskernel.a \
 ./Itaps/model/Makefile.am:             ${SIM_PSKRNL_LIB_DIR}/libpskernel.a \
 ./Itaps/mesh/Makefile.am:              ${SIM_PSKRNL_LIB_DIR}/libpskernel.a \
 > perl -pi -e 's/libpskernel.a/libpskernel.so/g' `find . -name Makefile.am`   
 grep "${SIM_PSKRNL_LIB_DIR}/libpskernel" `find . -name Makefile.am`          
 ./test/iGeom/test1/Makefile.am:        ${SIM_PSKRNL_LIB_DIR}/libpskernel.so \
 ./Itaps/common/Makefile.am:            ${SIM_PSKRNL_LIB_DIR}/libpskernel.so \
 ./Itaps/pmesh/Makefile.am:             ${SIM_PSKRNL_LIB_DIR}/libpskernel.so \
 ./Itaps/model/Makefile.am:             ${SIM_PSKRNL_LIB_DIR}/libpskernel.so \
 ./Itaps/mesh/Makefile.am:              ${SIM_PSKRNL_LIB_DIR}/libpskernel.so \


The following script, name it extreg.sh, will find and replace text as done above but will span multiple lines by undefining the record seperator $/. See http://www.ososo.de/extreg/ and http://perldoc.perl.org/perlvar.html for more info.

 #!/bin/bash 
 perl -we 'open FILE, "<'"$1"'" or die $!; undef $/;$_=<FILE>;'"$2"'; print $_'

Running on the following file, scatnu.F,

       dimension  ien(npro,nshl),       strl(npro,ngauss),
    &           xmudmi(npro,ngauss),       shp(nshl,ngauss)

with the command

 ./extreg.sh scatnu.F 's/\n     &/ & \n      /g' > scatnu_mod.F

will produce the file scatnu_mod.F which contains

     dimension  ien(npro,nshl),       strl(npro,ngauss), & 
                xmudmi(npro,ngauss),       shp(nshl,ngauss)
Personal tools