You are not logged in.
Hi I've been trying to replace a string in all directory names and all files but have been running into an issue with the string I'm trying to replace being present in both leading to errors along the lines of:
mv: './ships/sktest/sktestT6blocks.png' and './ships/sktest/sktestT6blocks.png' are the same file
Below is the loop I'm trying to use:
find . -type f -name "*$search*" | while read -r file; do
mv "$file" "${file//$search/$replace}" #2> /dev/null
done
Is there any way to exclude the directories in order to rename each separately or some other method to get it to work or do something similar?
Offline
Your going to have to be more specific. What are $search and $replace in this context and what do you want to happen? Given the -type f flag, I gather you'd want to operate just on the filename not the path - but if that's the case, the content of that loop is wrong - you'd likely want to break it into dirname and basename and do the replacement just on the basename component.
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Offline
$search and $replace are variables containing strings where $search contains the string to be replaced. How would I break it into the directory name and basename?
Full script below.
#!/bin/bash
@echo on
#Constants
RED='\033[0;31m'
NC='\033[0m'
search=sktest
#temporary
replace=testname
#Setup
echo "Linux port of DrPvtSkittles' Basic Race Template setup script by Patchouli Fleur"
echo -e "${RED}╔══════════════════════════════════════════════════════╗"
echo "║IT IS RECOMMENDED TO BACKUP YOUR MOD BEFORE CONTINUING║"
echo -e "╚══════════════════════════════════════════════════════╝${NC}"
#read -p "Enter the race's name: " replace
echo "╔═════════════════════════════════════════════════════════╗"
echo "║This could take several minuites depending on your system║"
echo -e "║ ${RED}DO NOT CLOSE THIS WINDOW${NC} ║"
echo "╚═════════════════════════════════════════════════════════╝"
#Actual work
#change what is in files
find . -type f -not -name "*.sh" -not -path '*/\.*' -exec sed -i "s/$search/$replace/g" {} +
#change filenames
#for file in * ; do mv $file ${file//$search/$replace} ; done
find . -type f -name "*$search*" | while read -r file; do
mv "$file" "${file//$search/$replace}" #2> /dev/null
done
Offline
directory name and basename?
# dir="$(dirname $file)"
# name="$(basename $file)"
Offline
$search and $replace are variables containing strings
No shit. I was asking what they were set to. I give up.
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Offline
Trilby wanted to know what *actual* patterns fail the replacement, eg. if they include tokens that would have required being escaped.
You're not required to explain bash basics here
Add "set -x" to your script to trace it and see what is actually expanded where.
Offline