got a virus? |
---|
PC Technician code to change text in multiple files
In this code example - I wanted to
make global changes to multiple files in a directory structure using
unix commands. This involves the use of two commands - "find" and "sed".
I wanted to write a general shell script to accomplish this. I found one example
that used a combination of first getting a list of files in a directory and its
directory substructure and then processing this list with a "do" loop
which used the sed command. I then came up with a simpler way to do this
without the "do" loop which also involved creating a temp file and then moving
it back to the original file (seems a bit clumsy).
So here's what I did - in the shell script. 1. Read in the starting directory where I wanted to change the files. 2. Read in the text strings - the old the replacement strings. 3. Develop the command to perform the work. This is described in the code example below: |
P.S. By the way, when I tried the global changes using the code based on first getting the list of files and then the do-loop to process the list - caused a problem. See the code below: --------------------------------------------------------------------------------- list=`find $FULL_DIR -type f ` for file in ${list} do #In the command below - the colon is a delimiter in the sed command # and obviously the old and new text cannot have this character in the strings. sed s:"${OLDTEXT}":"${NEWTEXT}":g ${file} > /tmp/temp.txt mv /tmp/temp.txt ${file} done ---------------------------------------------------------------------------------- What happened was the "mv" command changed file permissions on the .cgi and .pl files to read only , ie, it lost the execute bit on these files as a result of the creation of the temp file and the subsequent move command. So I then tried a global change to these files using the "chmod" command, ie, I tried this: chmod -R 755 *.cgi which theorectically should work to recursively change all files ending in .cgi to mode 755 for the current directory and below. Well it didn't, so I then tried a variation - which is coded as shown: find . -type f -name '*.cgi' -exec chmod 755 {} \; And this worked just fine. Note the similarity between this command and the find/sed command in the shell script in the white box above.If you need more info on shell scripting try HERE - Great tutorial site. |