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 of l (not recommended for variable names I'm pretty sure although I can't find a link (it can be confused with 1, 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.

Share:
6,319

Related videos on Youtube

Koshur
Author by

Koshur

Updated on September 18, 2022

Comments

  • Koshur
    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
      Sergiy Kolodyazhnyy over 7 years
      First of all, you don't need echo $(), just call wc directly
    • Sergiy Kolodyazhnyy
      Sergiy Kolodyazhnyy over 7 years
      Second, use $0 variable to skip the script itself.
  • Koshur
    Koshur over 7 years
    How do we ignore directories?
  • Matthias
    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