0

Can anyone help me finding solution to my requirement.

the requirement is I have to write a shell script which will scan a directory and read each file coming to it and will search for a string starts with (like "AB00732614") It will search for all files which contains AB* then it will move the file to another directory.

3
  • Why not just mv dir1/AB* dir2? Commented Mar 13, 2017 at 11:57
  • 1
    Is the string part of the filename or part of the contents of the file? Commented Mar 13, 2017 at 12:04
  • AB is string which is inside many files. Commented Mar 13, 2017 at 15:15

2 Answers 2

1

Assuming that the string AB-etc. is part of the contents of the files to be moved:

find /path/to/dir -type f -exec grep -qE 'AB[0-9]{8}' {} \; -exec mv -i {} /path/to/destination/ \;

This uses find to find all regular files under /path/to/dir. For each file, grep will look whether it contains anything matching the extended regular expression AB[0-9]{8} (the string AB followed by exactly eight digits). If it does, the file is moved to the directory /path/to/destination/.

If another file with the same name as the file being moved is already in the destination directory, you will have to confirm that you would like to overwrite that file.

0
0

You can use:

find . -type f -iname 'AB*' -exec mv -t ./another_directory/ {} \+

It is very well explained here: https://stackoverflow.com/a/5607677

2
  • Note that it's GNU specific and will also move files whose name starts with ab or Ab or aB (and will only move regular files, not the other types of files like directory, symlink, device, fifo...) Commented Mar 13, 2017 at 11:54
  • Thanks Mqtoto but it is not working.. Commented Mar 13, 2017 at 15:44

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.