3

Code

find /tmp/ -type f                                      \
    \( -name "*.h" \) -o \( -name "*.cpp" \) -o         \
    \( \! -name "*.bak" \) -exec                        \
    sed -i '1s/^/#include <stdint.h>\n/' {} +

I am not completely sure that this is the right way to go. I write directly to the file without taking temporary files. I want to replace the beginning of the line in .h and .cpp files with but not in .bak files.

How can you make efficient replacement? Note: I am using GNU sed.


I tried Terdon's command and the insertion is applied to wrong files:

$ cat test.sh 
gfind /tmp/ -type f   \
    \( -name "*.h" -o -name "*.cpp" -o ! -name "*.bak" \) \
    -exec gsed -i '1s/^/#include <stdint.h>\n/' {} +    
$ sh test.sh 
$ cat test.sh    
#include <stdint.h>
gfind /tmp/ -type f   \
    \( -name "*.h" -o -name "*.cpp" -o ! -name "*.bak" \) \
    -exec gsed -i '1s/^/#include <stdint.h>\n/' {} +

where all commands are GNU: find and sed.

1 Answers1

7

Try this:

find /tmp/ -type f  -name "*.h" -o -name "*.cpp"  \
           -exec  sed -i '1s/^/#include <stdint.h>\n/' {} +

Also, as correctly pointed out to me, the ! -name "*.bak" is superfluous. The -name *foo pattern only matches files ending with foo. Therefore, the *.cpp and *.h already exclude *.bak.

terdon
  • 242,166
  • Why {} \;? But not {} +? – Léo Léopold Hertz 준영 Jun 29 '15 at 12:11
  • @Masi well, my GNU find can deal with sed -i 's/foo/bar/ * on multiple files correctly (I have edited to use +). I didn't use it at first because I'm not sure that non-GNU sed can do that. – terdon Jun 29 '15 at 12:18
  • @Masi what command did you run? There is no _ there so I don't see how that message could have come from the one I show. – terdon Jun 29 '15 at 12:22
  • Error sed: 1: "/tmp/ ...": bad flag in substitute command: '_' only in BSD sed but not in GNU sed. I think it is enough to stay in GNU Sed. – Léo Léopold Hertz 준영 Jun 29 '15 at 12:22
  • @Masi well, yeah, that's what you get when you don't tell us your OS. Come on Masi! This is not the first time I've had to tell you to give us all information in the question. The syntax for BSD sed is quite different. For one thins it needs -i '' when you don't want a backup file. I also don't know if it supports the 1 flag or using -i on multiple files. – terdon Jun 29 '15 at 12:24
  • Forget BSD, let's stick to GNU. In GNU, something fails and badly. Every single file of the folder and its subfolders is put #include <stdint.h> with this command. I posted output below – Léo Léopold Hertz 준영 Jun 29 '15 at 12:25
  • 1
    @Masi try pasting the exact command I gave you. I also removed the unneeded ! -name "*.bak". – terdon Jun 29 '15 at 12:34
  • Yes, you are right, it is unnecessary in GNU find. I think everything works now. – Léo Léopold Hertz 준영 Jun 29 '15 at 12:36
  • @terdon Sure those parens are needed ? – 123 Jun 29 '15 at 12:53
  • @User112638726 nope, not sure at all :) Thanks. – terdon Jun 29 '15 at 17:34