theGrayFox
theGrayFox

Reputation: 931

Bash - Printing Directory Files

What's the best way to print all the files listed in a directory and the numer of files using a for loop? Is there a better of doing this?

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/$1"

for file in "$target"/*
do
  printf "%s\n" "$file" | cut -d"/" -f8
done

Upvotes: 5

Views: 39305

Answers (2)

user539810
user539810

Reputation:

target="/home/personal/scripts/07_22_13/ford/$1"
for f in "$target"/*; do
    basename "$f"
done | awk 'END { printf("File count: %d", NR); } NF=NF'

basename "$f" will automatically output each filename on its own line, and the awk code will print the total number of records processed, which is this case is the number of files listed. Additionally, awk will automatically print the filenames because of the NF=NF pattern at the end. I'd say learning awk can be advantageous, as shown here. :-)

Upvotes: 0

Hai Vu
Hai Vu

Reputation: 40723

Here is a solution:

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/$1"
let count=0
for f in "$target"/*
do
    echo $(basename $f)
    let count=count+1
done
echo ""
echo "Count: $count"

Solution 2

If you don't want to deal with parsing the path to get just the file names, another solution is to cd into the directory in question, do your business, and cd back to where you were:

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/$1"
pushd "$target" > /dev/null
let count=0
for f in *
do
    echo $f
    let count=count+1
done
popd
echo ""
echo "Count: $count"

The pushd and popd commands will switch to a directory, then return.

Upvotes: 8

Related Questions