0

I'm trying to do "one line script" or really small bash script.

It have to find file (for example ./xxx/one.php) and if that file exist edit (with printf or echo) other file IN SAME directory (for example ./xxx/test.php).

Right now I made second part - editing existing file, but I don't have idea how to, or where to enter "if".

Actually I have something like that

for file in `find . -name "test*.php"` ; do

(printf "It's me, on first line \n and me on second line\n" && cat $file) > "$file".bak && mv "$file".bak "$file"

done

It's should be something like this?

if [[ `find . -name "one*.php` ]]; do

for file in `find . -name "test*.php"` ; do

(printf "It's me, on first line \n and me on second line\n" && cat $file) > "$file".bak && mv "$file".bak "$file"

done
done
0

The -execdir option to find is handy here:

find -name 'one*.php' -execdir bash -c '
if [ -e test.php ] ; then
    printf ... && mv test.bak test.php
fi' {} \;

-execdir is

Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find.

-execdir will run the given command in the directory the found file was in, so the test.php file "next to" it will be right there to manipulate. Here we launch bash in that directory and run a small script there to make the manipulations you want. There's no need to complex path manipulations or re-finding the file. Above I check that the file exists, but if it will always be there (or you want to create it unconditionally) you can take the if out.

-execdir is a GNU find extension, not in POSIX, but you very likely have that given your tags. One caveat is that your PATH environment variable can't contain . or any other relative paths (including an empty element), for security reasons, so if your ambient one does you'll need to reset it first: PATH=... find ....

  • So because my PATH can't contain dot... it will by default search in current directory? – TheTanadu Apr 18 at 23:34
  • If you have a . or empty element in PATH, executables will be searched for in the current directory, but the default is that they are not. That part is just a caveat about when find -execdir will refuse to run, which is confusing to encounter otherwise. – Michael Homer Apr 18 at 23:36
  • Oh ok, thank you for explaining. – TheTanadu Apr 18 at 23:38
  • I found that when I pasted that into .sh executable file and run it I get bash skrypt.sh: line 4: unexpected EOF while looking for matching `"' skrypt.sh: line 6: syntax error: unexpected end of file – TheTanadu Apr 18 at 23:58
  • You're missing a closing ", somewhere. I don't know where, because that's something you've added, but the opening quote should be on line 4. – Michael Homer Apr 19 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.