Linux:删除不包含特定行数的文件

Dan*_*iel 5 linux

如何删除目录中具有多于或少于指定行数的文件(所有文件都有".txt"后缀)?

Kev*_*sen 11

这个bash脚本应该可以解决问题.保存为"rmlc.sh".

样品用法:

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
Run Code Online (Sandbox Code Playgroud)

请注意,如果rmlc.sh脚本位于当前目录中,则会对其进行保护以防删除.


#!/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
Run Code Online (Sandbox Code Playgroud)

  • +1 - 非常好,完整且文档齐全的脚本 (2认同)
  • 哈珀:我最初尝试过"wc -l".问题是输出包括文件名而不仅仅是行号.例如,"wc -l rmlc.sh"输出"48 rmlc.sh",而"echo rmlc.sh | wc -l"只输出"48". (2认同)

0x6*_*015 1

试试这个 bash 脚本:

LINES=10
for f in *.txt; do 
  if [ `cat "$f" | wc -l` -ne $LINES ]; then 
     rm -f "$f"
  fi
done
Run Code Online (Sandbox Code Playgroud)

(未测试)

编辑:使用管道输入 wc,因为 wc 也会打印文件名。