Script Gems

I’ve created this page in the hope that I’ll be able to find a solution to a problem I’ve had before, without doing the 3 hours of research to solve it in the first place.

Search and replace text in multiple files recursively

I found several answers to this, but the best was Michael Slade’s answer at Stack Overflow – I needed to include path characters (slashes /) so I modified it slightly to use a comma (,) as the delimiter

find . -type f -print0|xargs -0 perl -p -i -e "s,searchstring,replacestring,g;"

Searching for escaped characters

But that was not the whole answer, because my search string also has escaped characters, like `\&` and `\ ` (Spaces). So the command

find . -type f -print0|xargs -0 perl -p -i -e "s,/opt/GNS3/READMEs\ \&\ Scripts/WorkBench\ scripts/startup,~/GNS3/WorkBench/Scripts/startup,g;"

didn’t work – I had to change it to:

find . -type f -print0|xargs -0 perl -p -i -e "s,/opt/GNS3/READMEs\\\ \\\&\\\ Scripts/WorkBench\\\ scripts/startup,~/GNS3/WorkBench/Scripts/startup,g;"

Spawn a shell, run a command and keep the shell open

Thanks to

gnome-terminal -e "bash -c \"mycommand; exec bash\""

Recursively rename a set of similar files

Thanks to SvW’s contribution at
To rename all files beginning with the word “Instructions” to now begin with “instructions” instead, I used this command:

find . -name "Instructions*" -print0 | xargs -0 rename "s/Instructions/instructions/"

About RedNectar Chris Welsh

Professional IT Instructor. All things TCP/IP, Cisco or VoIP
This entry was posted in escaped characters, find, perl, Programming, scripts, xargs and tagged , . Bookmark the permalink.