Count number of lines in each file within current directory using a for loop?
6,319
I think you almost got it. You can use basename "$0"
to find the name of the script from within the script, and print the line count of everything except that
#!/bin/bash
if [ $# -eq 0 ]
then
for k in *
do
if [[ ! -d "$k" && "$k" != `basename "$0"` ]]
then
wc -l "$k"
fi
done
else
for k in $*
do
wc -l "$k"
done
fi
I took the liberty of
- Using
k
instead ofl
(not recommended for variable names I'm pretty sure although I can't find a link (it can be confused with1
,I
)) - Using 4 spaces for indentation instead of 8. In the end that is of course your decision, but I'd say 4 are more readable than 8.
- Quoting your variables. Highly recommended to avoid splitting variable names with spaces.
- Dropping the unnecessary
echo
like @Serg pointed out.
EDIT I added double brackets and a test for directories to ignore them as well to the if
conditional.
Related videos on Youtube
![Koshur](https://lh6.googleusercontent.com/-5AO-AY4sOtc/AAAAAAAAAAI/AAAAAAAAAVc/3igN9St85II/photo.jpg?sz=256)
Author by
Koshur
Updated on September 18, 2022Comments
-
Koshur almost 2 years
- If a parameter is provided as an input, script should only check number of lines for that input file, otherwise script should display number of lines for each file within that directory.
- The script file should be ignored i.e. the count for the script file should not be displayed.
I tried:
#!/bin/bash if [ $# -eq 0 ] then for l in *.txt do echo $(wc -l $l) done else for l in $* do echo $(wc -l $l) done fi
But I am not allowed to explicitly mention the file type i.e *.txt - it must check all files except script file.
-
Sergiy Kolodyazhnyy over 7 yearsFirst of all, you don't need
echo $()
, just callwc
directly -
Sergiy Kolodyazhnyy over 7 yearsSecond, use
$0
variable to skip the script itself.
-
Koshur over 7 yearsHow do we ignore directories?
-
Matthias over 7 years
if [ ! -d "$k" ]
,-d
stands for directory. I'll modify my answer. I needed to change it to double brackets to get this to work