Search code examples
linuxunixfindsolaris

How to use find and echo to append a file


Hi this is my filesystem so far, and what I would like to achieve is to append "Hello world" in every text file that has 1 within its name.

root@s11:~/Test# ls -R

.: A B

./A: A1 A2

./B: B1 B2

What I did so far is

root@s11:~/Test# find . -iname "*1" -exec echo "Hello World" >> {} \;

root@s11:~/Test# find . -iname "*1" -exec file {} \;

./A/A1: empty file

./B/B1: empty file

My machine is Solaris 11.3


Solution

  • What you pass to -exec is a program to execute and individual arguments. In particular, you do NOT pass a shell command.

    However, >> is a shell construct, so if you want to use it, you need to run a shell:

    find . -iname '*1*' -exec sh -c 'echo "Hello World" >> {}' \;
    

    Here, the individual arguments being passed to -exec are sh, -c, echo "Hello World" >> {}, allowing you to run a shell command.

    Also note that I did -ianme '*1*' since your question said "has 1 within its name" rather than "ends with 1".