I have to write a shell script that creates a file containing the name of each text files from a folder (given as parameter) and it's subfolders that contain words longer than n characters (read n from keyboard).
I wrote the following code so far :
#!/bin/bash
Verifies if the first given parameter is a folder:
if [ ! -d $1 ]
then echo $1 is not a directory\!
exit 1
fi
Reading n
echo -n "Give the number n: "
read n
echo "You entered: $n"
Destination where to write the name of the files:
destinatie="destinatie"
the actual part that i think it makes me problems:
nr=0;
#while read line;
#do
for fisier in `find $1 -type f`
do
counter=0
for word in $(<$fisier);
do
file=`basename "$fisier"`
length=`expr length $word`
echo "$length"
if [ $length -gt $n ];
then counter=$(($counter+1))
fi
done
if [ $counter -gt $nr ];
then echo "$file" >> $destinatie
fi
done
break
done
exit
The script works but it does a few more steps that i don't need.It seems like it reads some files more than 1 time. If anyone can help me please?
I found the problem.The problem was the directory in which i was searching.Because i worked on the files from the direcotry and modified them , it seems that there remained some files which were not displayed in file explorer but the script would find them.i created another directory and i gived it as parameter and it works. Thank you for your answers .
This code has syntax errors, probably leftovers from your commented-out
while
loop: It would be best to remove the last 3 lines:done
causes the error,break
andexit
are unnecessary as there is nothing to break out from and the program always terminates at its end.The program appears to output files multiple times because you just append to
$destinatie
. You could simply delete that file when you start:You echo the numbers to stdout (
echo "$length"
) and the file names to$destinatie
(echo "$file" >> $destinatie
). I do not know if that is intentional.Does this help?
Some explanation:
\w
means: a character that words consist of{$n,}
means: number of consecutive characters is at least$n
Option
-l
lists files and does not print the grepped text and-r
performs a recursive scan on your directory in$1
Edit:
a bit more complete version around the egrep command: