Wednesday, 15 January 2025

bash scan file and lines

#!/bin/bash


# Check if a directory is provided as an argument

if [ -z "$1" ]; then

  echo "Usage: $0 <directory>"

  exit 1

fi


# Initialize total line count

total_lines=0


# Output header

echo -e "File Name\tTotal Lines"


# Loop through all files in the directory and its subdirectories

while IFS= read -r file; do

  # Count total lines in the current file

  line_count=$(wc -l < "$file")

  

  # Add to total line count

  total_lines=$((total_lines + line_count))

  

  # Print file name and line count

  echo -e "$(realpath "$file")\t$line_count"

done < <(find "$1" -type f)


# Output total line count

echo -e "\nTotal Lines: $total_lines"


// Optional paramter to skip folders


./scan_total_lines_skip_paths.sh /path/to/directory "folder1,folder2/nested"


//


#!/bin/bash


# Check if a directory is provided as an argument

if [ -z "$1" ]; then

  echo "Usage: $0 <directory> [exclude_paths]"

  exit 1

fi


# Initialize variables

directory="$1"

exclude_paths="$2"

total_lines=0


# Convert the comma-separated exclude_paths into find exclude arguments

exclude_args=()

if [ -n "$exclude_paths" ]; then

  IFS=',' read -ra paths <<< "$exclude_paths"

  for path in "${paths[@]}"; do

    exclude_args+=(-path "$directory/$path" -prune -o)

  done

fi


# Output header

echo -e "File Name\tTotal Lines"


# Loop through all files in the directory, excluding specified paths

while IFS= read -r file; do

  # Count total lines in the current file

  line_count=$(wc -l < "$file")

  

  # Add to total line count

  total_lines=$((total_lines + line_count))

  

  # Print file name and line count

  echo -e "$(realpath "$file")\t$line_count"

done < <(find "$directory" "${exclude_args[@]}" -type f -print)


# Output total line count

echo -e "\nTotal Lines: $total_lines"


No comments:

Post a Comment