开发者

Move all images in folder to subfolder, and update all references in text files to those images to their new location?

开发者 https://www.devze.com 2023-02-15 00:37 出处:网络
I have a folder which contains a ~50 text files (PHP) and hundreds of images. I would like to move all the images to a subfolder, and update the PHP files so any reference to those images point to the

I have a folder which contains a ~50 text files (PHP) and hundreds of images. I would like to move all the images to a subfolder, and update the PHP files so any reference to those images point to the new subfolder.

I know I can move all the images quite easily (mv *.jpg /image, mv *.gif /image, etc...), but don't know how t开发者_Go百科o go about updating all the text files - I assume a Regex has to be created to match all the images in a file, and then somehow the new directory has to be appended to the image file name? Is this best done with a shell script? Any help is appreciated (Server is Linux/CentOs5)

Thanks!


sed with the -i switch is probably what you're looking for. -i tells sed to edit the file in-place.

Something like this should work:

find /my/php/location -name '*.php' | xargs sed -ie 's,/old/location/,/new/location/,g'


You could do it like this:

#!/bin/sh
for f in *.jpg *.png *.gif; do 
    mv $f gfx/
    for p in *.txt; do 
        sed -i bak s,`echo $f`,gfx/`echo $f`,g $p 
    done 
done

It finds all jpg/png/gif files and moves them to the "gfx" subfolder, then for each txt file (or whatever kind of file you want it edited in) it uses "sed" in-place to alter the path.

Btw. it will create backup files of the edited files with the extra extension of "bak". This can be avoided by omitting the "bak" part in the script.


This will move all images to a subdir called 'images' and then change only links to image files by adding 'images/' just before the basename.

mkdir images
mv -f *.{jpg,gif,png,jpeg} images/
sed -i 's%[^/"'\'']\+\.\(gif\|jpg\|jpeg\|png\)%images/\0%g' *.php

If you have thousands of files, you may need to utilize find and xargs. So, a bit slower

find ./ -regex '.*\(gif\|jpg\|png\|jpeg\)' -exec mv {} /tmp \;
find ./ -name \*.php -print0 | \
xargs -0 sed -i 's%[^/"'\'']\+\.\(gif\|jpg\|jpeg\|png\)%images/\0%g' *.php

Caution, it will also change the path to images with remote urls. Also, make sure you have a full backup of your directory, php syntax and variable names might cause problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消