I have this files into a folder:


Inside of each .txt file I have a value that indicate the order was unpaid, what I need is clear the log folder for unpaids orders, for example I use this command to a output.sh for check before run:

find /log/users/ -name '*.txt' | xargs grep -l unpaid | awk '{print "mv "$1" /tmp/ }' >> clearlog.sh

What I need is to print for example this:

mv /log/users/Enero.01200.2019.txt /tmp/ && mv /log/users/Enero.01200.2019.pdf /tmp/ && mv /log/users/Enero.01200.2019.png /tmp/

If somebody have a better way to doit but asking for confirmation or a way to see what will move, I will aprecite it.

There is about 2,500 files to clear and I wont do a mess deleting wrong files.

Note: all txt files had a PDF and PNG related file. Im working in ubuntu 20.04 server

Thanks in advance!

  • Do you really need to find (recursively descend) the directory - or are all the files at one level? – steeldriver Nov 14 '20 at 22:46
  • I dont know, I only have one level "/log/users/" – valeria carrillo Nov 14 '20 at 22:52

If all the files are in a single directory level, would suggest a simple shell loop that conditionally moves the files based on the grep exit status, like

for f in /log/users/*.txt; do
  grep -q unpaid "$f" && echo mv -t /tmp/ -- "$f" "${f%.txt}.pdf" "${f%.txt}.png"

(remove the echo once you are happy that it's doing the right thing).

If you need to recursively descend the parent directory with find, then similarly

find /log/users/ -name '*.txt' -exec sh -c '
  for f do grep -q unpaid "$f" && echo mv -t /tmp/ -- "$f" "${f%.txt}.pdf" "${f%.txt}.png"; done
' find-sh {} +
  • Hi steeldriver, the solution works fine, I just need another option, is there a way to echo also the all line content, example the file Enero.202020.01.txt contains this line "CustomerID=405060 OrderStatus=unpaid" I need to echo all this line, thanks – valeria carrillo Nov 16 '20 at 22:16
  • @valeriacarrillo remove the -q option from the grep command - consider replacing it with -m1 if you only want to echo the first match (and avoid processing the remainder of the file) – steeldriver Nov 16 '20 at 22:20

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.