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 files and folders can contain white spaces and umlauts.
- 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 copycp
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
EDIT II: Going on with the solution from tripleee:
#!/bin/bash
grep . $1 | while read -r id; do
echo "Der Suchbegriff lautet:"$id; echo;
find /home/alex/testzone -name "$id*" -exec cp {} /home/alex/testzone/ausgabe \;
done
In case my ids.txt file contains empty lines the -name "$id*"
will be -name *
which in turn finds all files and copies all files.
Trying to prevent empty line to be read does not seem to work. They should be filtered by the expression grep . $1 |
. What am I doing wrong?