Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: delete files that don't contain specific number of lines

Tags:

linux

How to remove files inside a directory that have more or less lines than specified (all files have ".txt" suffix)?

like image 750
Daniel Avatar asked Jun 01 '09 15:06

Daniel


1 Answers

This bash script should do the trick. Save as "rmlc.sh".

Sample usage:

rmlc.sh -more 20 *.txt   # Remove all .txt files with more than 20 lines
rmlc.sh -less 15 *       # Remove ALL files with fewer than 15 lines

Note that if the rmlc.sh script is in the current directory, it is protected against deletion.


#!/bin/sh

# rmlc.sh - Remove by line count

SCRIPTNAME="rmlc.sh"
IFS=""

# Parse arguments 
if [ $# -lt 3 ]; then
    echo "Usage:"
    echo "$SCRIPTNAME [-more|-less] [numlines] file1 file2..."
    exit 
fi

if [ $1 == "-more" ]; then
    COMPARE="-gt" 
elif [ $1 == "-less" ]; then
    COMPARE="-lt" 
else
    echo "First argument must be -more or -less"
    exit 
fi

LINECOUNT=$2

# Discard non-filename arguments
shift 2

for filename in $*; do
    # Make sure we're dealing with a regular file first
    if [ ! -f "$filename" ]; then
        echo "Ignoring $filename"
        continue
    fi

    # We probably don't want to delete ourselves if script is in current dir
    if [ "$filename" == "$SCRIPTNAME" ]; then
        continue
    fi

    # Feed wc with stdin so that output doesn't include filename
    lines=`cat "$filename" | wc -l`

    # Check criteria and delete
    if [ $lines $COMPARE $LINECOUNT ]; then
        echo "Deleting $filename"
        rm "$filename"
    fi 
done
like image 51
Kevin Ivarsen Avatar answered Sep 30 '22 19:09

Kevin Ivarsen