Home » Questions » Computers [ Ask a new question ]

Find Files With Similar Name to Folder

Find Files With Similar Name to Folder

I'm on OS X, and I have a folder that contains a number of subfolders. There are two things I want to do. The first is to ensure that each subfolder has a file in it of the form [subfolder-name].grade.xml, then I need to search and replace within the appropriate file to make a couple of changes.

Asked by: Guest | Views: 335
Total answers/comments: 1
Guest [Entry]

"#!/bin/bash

# Get directory name from argument, default is .
DIR=${1:-.}

# For each subfolder in DIR (maxdepth limits to one level in depth)
find ""${DIR}"" -maxdepth 1 -type d | while read dir; do
# Check that there is a file called $dir.grade.xml in this dir
dirname=$(basename ""${dir}"")
gradefile=""${dirname}""/""${dirname}"".grade.xml
if [ -e ""${gradefile}"" ]; then
sed -i .bak ""s/foo/bar/g"" ""${gradefile}""
else
echo ""Warning: ${dir} does not contain ${gradefile}""
fi done

Minor tweaks around Raphink's framework.

Key points:

check directly for file existence with [ -e filename ] rather than running ls
put all variables in ${variablename}; often not strictly neccessary, but avoids ambiguity (${variablename} and ${variable}name are clearly distinct, $variablename could mean either)
pass an extension to sed to make backup files. This is both good practice (in case your munging goes wrong), and, on OSX, mandatory (raphink's version interprets s/foo/bar/g as being the extension you want on the backup files, then tries to parse the filename as a command.
Okay, I lied, it's not actually mandatory - you could use sed -i """" ""s/foo/bar/g"" ${gradefile} to pass an empty extension, which would cause sed not make a backup."