[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2714
  • Last Modified:

How to search and replace text within all UNIX files, filenames and directories (AIX 5.2)

I want to search thru every directory. filename and file, looking for a particular text (let's say we're looking for RECO).  Then, when RECO (either upper or lower case)  is found within the body of a file, I want to first make a copy of  that file,  to the same directory, with another extension added to the filename (original_name.txt.orig) and then replace RECO (within the original file) with UPGRD.  In addition, if there are directories or filenames that have the same text (RECO) in them, I want to write the original  directory name or filename to a file (in order to track what was changed),  then replace the text RECO in the directory or filename with UPGRD. I'm using UNIX on AIX 5.2.  I'm just coming back to using UNIX and I'm not quite to par with scripting.
1 Solution
Are you sure you want to perform this operation on directories? I don't think so. Let's exclude them. After all directories contain filenames. If you replace text in a directory you are causing potential problems and you don't want that.

find $DIR -type f | xargs grep RECO 2>/dev/null | cut -d: -f1 | sort | uniq | while read PATH
sed <${PATH} >${PATH}.new -e 's/RECO/UPGRD/g'
mv ${PATH} ${PATH}.orig
mv ${PATH}.new ${PATH}

This does the first part, though not quite as you specified. For the "in addition", are you asying that RECO can be in the file name also? If so then can the file contain RECO too? If so,

find $DIR - type f | grep RECO | while read PATH
NEWPATH=$(echo $PATH | sed -e 's/RECO/UPGRD/g')
echo $PATH >/tmp/yourlogfile

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now