[Gllug] C and Unix pioneer Dennis Ritchie reported dead

James Hawtin oolon at ankh.org
Tue Nov 1 14:58:40 UTC 2011


tid wrote:
> A colleague asked my opinion as to whether I felt the following was a 
> correct answer to an test question:
>
>   Q: Please supply a one-line command to substitute all occurences of 
> 'fish' to 'chips' in all files ending in .html
>  
>  -A: $ for i in *.html ; do sed -i -e 's/fish/chips/g' $i ; done
>
I think it is valid I see no reason why a for loop is worse than say

find . -name "*.html" -exec sed -i -e 's/fish/chips/g' '{}' \;

However this is ALSO wrong... it should be

find . -name "*.html" -exec sed -i -e 's/fish/chips/g' -- '{}' \;

because it would not work with "-r hello.html" or "hello world.html"

$ ls -l
total 0
-rw-rw-r-- 1 oolon ankh 0 Nov  1 14:43 fish.html.fred
-rw-rw-r-- 1 oolon ankh 0 Nov  1 14:52 fred.html
-rw-rw-r-- 1 oolon ankh 0 Nov  1 14:51 hello world.html
-rw-rw-r-- 1 oolon ankh 0 Nov  1 14:51 -r hello.html

for i in *.html ; do sed -i -e 's/fish/chips/g' $i ; done
sed: can't read hello: No such file or directory
sed: can't read world.html: No such file or directory
sed: can't read hello.html: No such file or directory

Personally I hate using -exec (not sure why) and generally do a "find | 
while read" insted, because a for loop from a glob has a finite number 
of argument it can handle (however it is very large with linux these days).

James
--
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list