LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Recursively rename some files (https://www.linuxquestions.org/questions/programming-9/recursively-rename-some-files-891191/)

grail 07-12-2011 07:29 PM

I agree with MTK, this is not difficult and a solution has been presented to rename the objects.
Here is another alternative:
Code:

while read -r line
do
    dir=${line%/*}/
    name=${line##*/}

    mv "$line" "$dir${name//AA/BB}"
done< <(find Dir1 -depth -name '*AA*')

As for the sed, have a look at the -i option. If using something like the above, I would probably test if a file prior
to move and perform sed then.

mail4mz 07-12-2011 09:20 PM

Yeah, I want to rename files and change the contents that match certain patterns. Since I have many levels of directories; the contents changes are complex, I plan to use "sed -f" to do it. Any suggestion?

grail 07-12-2011 11:03 PM

I am not sure I understand your most recent question? What suggestion do you require? The '-f' option
sounds fine if you already have the changes mapped out in a file.

MTK358 07-13-2011 06:43 AM

How about this:

Code:

while read file
do
    mv "$file" "$(dirname "$file")/$(basename "$file" | sed 's/AA/BB/g')"
    if [[ ! -d $file ]]
    then
        # edit the file with sed
    fi
done < <(find Dir1 -depth)


mail4mz 07-13-2011 08:12 AM

My question is how to use SED to change the contents of multiple files. The shell does allow me to use sed with both input and output are the same file as following:
sed 's/AA/ZZ/g' < $sourcefile > $sourcefile


As to the script you suggested, it failed when I tried as followings:

while read -r sfile
do
echo "sfile=$sfile"
done<< ( find $1 -depth )

The error message is:
line 4: syntax error near unexpected token '('
line 4: `done<< (find $1 -depth)`

MTK358 07-13-2011 08:23 AM

Quote:

Originally Posted by mail4mz (Post 4413746)
My question is how to use SED to change the contents of multiple files. The shell does allow me to use sed with both input and output are the same file as following:
sed 's/AA/ZZ/g' < $sourcefile > $sourcefile

Use sed's "-i" option:

Code:

sed -i 's/AA/ZZ/g' "$sourcefile"
Also, as I said, always double-quote variables that contain a filename.

Quote:

Originally Posted by mail4mz (Post 4413746)
As to the script you suggested, it failed when I tried as followings:

while read -r sfile
do
echo "sfile=$sfile"
done<< ( find $1 -depth )

The error message is:
line 4: syntax error near unexpected token '('
line 4: `done<< (find $1 -depth)`

You typed it wrong. What I said:

Code:

done < <(
What you wrote:

Code:

done<< (
Also, use code tags when posting code.

mail4mz 07-15-2011 10:18 AM

It works well. Thanks you MTK!!


All times are GMT -5. The time now is 01:07 AM.