I have a variable which stores file names as a result of find command. I need to delete all these files one by one, i.e. by a loop. Can anyone tell me how can it be done?
The variable
f2d
has the file names like these
abc.txt
bcd.txt
fff.txt
gef.txt
Now I have used a loop as below;
for i in $f2d
do
rm $i
done
But this is not giving me the desired output. It is taking all the files at a time and not interating through the loop. Please advise.
ran:/home/vbe $ echo $0
sh
ran:/home/vbe $ echo "$f2d"
abc.txt
bcd.txt
fff.txt
gef.txt
ran:/home/vbe $ for i in $f2d^Jdo ^J echo " Arg is = $i "^Jdone
Arg is = abc.txt
Arg is = bcd.txt
Arg is = fff.txt
Arg is = gef.txt
ran:/home/vbe $
As pamu already shown previously...
So if it does not work, then you havent given us the exact value in the variable I suspect a line feed or newline with end of line... OR:
Look again carefully at pamu's post... specially the second part... doesnt that remind you of something?
ran:/home/vbe $ for i in "$f2d"^Jdo ^J echo " Arg is = $i "^Jdone
Arg is = abc.txt
bcd.txt
fff.txt
gef.txt
Yes, I am using IFS at an earlier place and it is very much required there. The below piece of code shows that.
IFS=' '
while read -r dir; do
(
cd $dir
files2del=$(find ./ -type d ! -name . -prune -o -mtime +$NUM_DAYS -name '*.dat' )
echo "$files2del"
for i in $files2del
do
echo "Arg is ="
done
)
done < dirlist_1.txt
Could you please advise how do I get the for loop correct.
You can just specify IFS for the read instead of changing it for the entire program:
while IFS=" " read -r dir; do
(
cd $dir
files2del=$(find ./ -type d ! -name . -prune -o -mtime +$NUM_DAYS -name '*.dat' )
echo "$files2del"
for i in $files2del
do
echo "Arg is ="
done
)
done < dirlist_1.txt
This should let $files2del split on any whitespace.
But really, you shouldn't be putting an open-ended list like that into a variable. I don't think you need to cd either.
while IFS=" " read -r dir
do
find "$dir" -type d ! -name . -prune -o -mtime +$NUM_DAYS -name '*.dat' | while read i
do
echo "got file $i"
done
done < dirlist_1.txt