[Gllug] error in bash script to rename files in a directory

Tethys tet at accucard.com
Tue Dec 31 13:07:46 UTC 2002


Stig Brautaset writes:

>> 	for i in *
>> 	do
>> 		sed 's/php3/php/g' "$i" > "$i.$$"
>> 		[ -s "$i.$$" ] && mv "$i.$$" "$i"
>> 	done
>
>You have to admit that this isn't exactly pretty.

True. In fact, it's almost worthy of perl in its ugliness :-) It could
be slightly improved visually at the expense of brevity:

	for file in *
	do
		tmpfile="$file.$$"

		sed 's/php3/php/g' "$file" > "$tmpfile"
		if [ -s "$tmpfile" ]
		then
			mv "$tmpfile" "$file"
		fi

		/bin/rm -f "$tmpfile" 2>/dev/null
	done

Or even more, at the expense of error checking and efficiency:

	for file in *
	do
		sed 's/php3/php/g' "$file" > /tmp/foo
		mv /tmp/foo "$file"
	done

But I'll conceed that even that's still not great...

>I've found myself many times wanting a 'same file' flag to sed. That
>would ease these cases a bit, but I'm not sure it's a good idea for
>other reasons.

4.2BSD used to have an "over" command that overwrote a file after
performing an action of your choice on it, but I haven't seen it
since. Incidentally, the "over" command that comes with some Linux
distributions is different...

Tet

-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list