-1

How can I select files one by one from a list and work on them? This is my code:

list=$( find $path \( -name "*.c" -or -name "*.cpp" -or -name "*.cxx" -or -name "*.cc" \) )
for file in "$list"
do
done
tink
  • 14,342
  • 4
  • 46
  • 50
katoutou
  • 11
  • 3
  • Depends on what you are trying to do but the -exec flag in find may be beneficial to you. – Raman Sailopal Nov 15 '20 at 21:58
  • I collect every file with these extensions and then move them one-by-one to another destination.. But some filenames contain whitespace.. How can i use -exec here? – katoutou Nov 15 '20 at 22:00

2 Answers2

1

You can pass to find as many commands as you like:

find $path \( -name "*.c" -or -name "*.cpp" -or -name "*.cxx" -or -name "*.cc" \) \
    -exec bash -c "echo cmd1 '{}'; echo cmd2 '{}'; echo etc." \;

an alternative is to write a function:

function safe_copy() {
  echo "$1"     
}          

export -f safe_copy

find $path \( -name "*.c" -or -name "*.cpp" -or -name "*.cxx" -or -name "*.cc" \) \
     -exec bash -c "safe_copy '{}'" \;

You can also write a script and call it with exec instead of a function.

perreal
  • 94,503
  • 21
  • 155
  • 181
0

You can use -print0 as find argument, to print a null delimited stream of filenames.

Then loop read the null delimited stream.

find "$path" \( -name '*.c' -or -name '*.cpp' -or -name '*.cxx' -or -name '*.cc' \) -print0 |
while IFS= read -r file
do
done
Léa Gris
  • 17,497
  • 4
  • 32
  • 41