Home > OS >  How to read out a file line by line and for every line do a search with find and copy the search res
How to read out a file line by line and for every line do a search with find and copy the search res

Time:02-02

I hope you can help me with the following problem:

The Situation

  • I need to find files in various folders and copy them to another folder.
  • The filenames contain an ID and a string like: "2022-01-11-02 super important file"
  • The filenames I need to find are collected in a textfile named ids.txt. This file only contains the IDs but not the whole filename as a string.

What I want to achieve:

  • I want to read out ids.txt line by line.
  • For every line in ids.txt I want to do a find search and copy cp the result to destination.

So far I tried:

  • for n in $(cat ids.txt); do find /home/alex/testzone/ -name "$n" -exec cp {} /home/alex/testzone/output \; ;
  • while read -r ids; do find /home/alex/testzone -name "$ids" -exec cp {} /home/alex/testzone/output \; ; done < ids.txt

The output folder remains empty. Not using -exec also gives no (search)results.

I was thinking that -name "$ids" is the root cause here. My files contain the ID a String so I should search for names containing the ID plus a variable string (star)

  • As argument for -name I also tried "$ids *" "$ids"" *" and so on with no luck.

Is there an argument that I can use in conjunction with find instead of using the star in the -name argument?


Do you have any solution for me to automate this process in a bash script to read out ids.txt file, search the filenames and copy them over to specified folder?

In the end I would like to create a bash script that takes ids.txt and the search-folder and the output-folder as arguments like:

my-id-search.sh /home/alex/testzone/ids.txt /home/alex/testzone/ /home/alex/testzone/output 

EDIT: This is some example content of the ids.txt file where only ids are listed (not the whole filename):

2022-01-11-01
2022-01-11-02
2020-12-01-62

CodePudding user response:

I have succesfully used the following command

for n in $(cat files.txt); do (cp ./start/$n ./finish) ; done

which copies all the files named in files.txt from ./start to ./finish

#a full sample script to set the stage
mkdir start finish
cd start
touch one.txt two.txt one.jpg two.jpg
ls > ../files.txt
touch one.java two.java
cd ..

CodePudding user response:

#Please try the following bash script copier.sh
#!/bin/bash
for n in $(cat files.txt); do (                           
    du -a | awk '{ print $2 }' | grep $n | xargs -I '{}' cp '{}' finish
    );
done
# which copies recursively all the files named in files.txt from . and it's subfiles to ./finish
  •  Tags:  
  • Related