1

I want to find *.json2 files , check if they r executed if no execute POST.

I have

1.json2
2.json2  2.json2.ml
3.json2  3.json2.ml

I use this command

find . -type f -name '*.json2' | if [{}.ml]; then -exec sh -c 'curl -X POST -H "Content-Type: application/json" -d @{} https://api.myweb.com/api > {}.ml' \;

I want to execute only the file dont have ml extension. Thx

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Jess
  • 25

2 Answers2

0

Have you considered using xargs?

find . -type f -name '*.json2' | xargs bash -c 'for fname; do if [ ! -e ${fname}.ml ]; then curl -X POST -H "Content-Type: application/json" -d @${fname} https://api.myweb.com/api > ${fname}.ml; fi; done' bash

As for that trailing bash, it's a 'trick' I just learned on the xargs wikipedia page. (It has to be there or the first argument isn't processed.) I admit I'd never used that before, but I did test it with an echo command and some test files, and it seems to do what you want.

  • It's not a trick, it's that argument that gets put into $0. – Kusalananda Aug 29 '18 at 10:17
  • I explained that; I called it a trick following the reference I gave. Why was my answer downvoted? It follows the basic pattern laid out by the OP, it is concise and SFAIK (I can't test their curl command) it works. – flaysomerages Aug 29 '18 at 13:44
0
find . -type f -name '*.json2' -exec sh -c '
    for pathname; do
        [ -e "$pathname.ml" ] && continue
        curl -X POST -H "Content-Type: application/json" -d @"$pathname" https://api.myweb.com/api >"$pathname.ml"
    done' sh {} +

This would find all regular files whose filenames match the pattern *.json2 in or below the current directory. For batches of these files, a short shell script is executed. This script tests, for each pathname given to it by find, whether there's a .ml file corresponding to the pathname. If there is not, your curl command is executed.

This could be simplified into the following if all files are located in the current directory only:

for pathname in ./*.json2; do
    [ -e "$pathname.ml" ] && continue
    curl -X POST -H "Content-Type: application/json" -d @"$pathname" https://api.myweb.com/api >"$pathname.ml"
done

Note that this is essentially exactly the same loop as in the script called by find. The only difference is that in the first example, find act as a pathname generator for the loop, while in the shorter example, the pathnames are generated using a globbing pattern (and only from the current directory).

Related:

Kusalananda
  • 333,661