I am trying to:

  1. Find a string "required accuracy" in all files(file name: OUTCAR.txt) in all my subdirectories(approximately 50 folders).

  2. Copy only the folders which have files with the searched-for the string to another location

My solution at this time:

1. grep -r "required accuracy" 

I would like to search only in files named OUTCAR though. Otherwise, I have two files from one folder on my list.

2. grep -r "required accuracy" OUTCAR -exec scp -r {} ./final location

I have no idea at all how to extract the folder list from the list of files that I found with the grep command. Maybe it is possible to use the find command for strings in files?

  • How many level of directories do u have and will the file is available only at the end of the tree?
    – Siva
    Apr 24, 2020 at 10:45
  • 1
    I basically have one folder "rel1" then in this folder I have 50 folders ( folders with names 1 to 50) with no subdirectories. In each of these folders 1 to 50 there is one OUTCAR.txt. In these OUTCAR.txt the string I am looking for is sometimes there and sometimes not. I want to copy all the folders which contain the files with the the string I am looking for to another folder "rel1_fin".
    – Jennifer
    Apr 24, 2020 at 10:55

3 Answers 3


If your find has -execdir available:

find . -type f -name "OUTCAR.txt" \
-exec grep -q "required accuracy" {} \;
-execdir scp -r ./ "/path/to/final location" \;
  • find all files (-type f) with -name OUTCAR.txt.
  • grep for "required accuracy" in that file,
  • If grep is successful, run scp ... from the directory, that the file is in using -execdir.

Note, that /path/to/final/location should be an absolute path, or you may use $PWD/relative/path/from/where/find/is/executed.

  • -execdir is a non-standard feature.
    – schily
    Apr 24, 2020 at 12:16

Try this,

 grep -lr 'required accuracy' rel1 | sed 's#/OUTCAR.txt##g' | xargs -I {} mv {} rel1_fin
  • -l Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match
  • Thank you! This code works :.).
    – Jennifer
    Apr 24, 2020 at 13:00

I think this may help :

grep -Rl "required accuracy"  ./Source-dir/* | grep OUTCAR | xargs -I[] bash -c 'val="[]";scp -r ${val%/*} user@doman:/destination-direcory'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .