簡體   English   中英

Linux:刪除不包含特定行數的文件

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

如何刪除目錄中具有多於或少於指定行數的文件(所有文件都有“.txt”后綴)?

這個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

請注意,如果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

玩了一下0x6adb015的答案。 這對我有用:

LINES=10
for f in *.txt; do
  a=`cat "$f" | wc -l`;
  if [ "$a" -ne "$LINES" ]
  then
    rm -f "$f"
  fi
done

這個班輪也應該這樣做

 find -name '*.txt' | xargs  wc -l | awk '{if($1 > 1000 && index($2, "txt")>0 ) print $2}' | xargs rm

在上面的示例中,將刪除大於1000行的文件。

選擇>和<以及相應的行數。

試試這個bash腳本:

LINES=10
for f in *.txt; do 
  if [ `cat "$f" | wc -l` -ne $LINES ]; then 
     rm -f "$f"
  fi
done

(未測試)

編輯:使用管道輸入wc,因為wc也打印文件名。

我的命令行mashing非常生疏,但我認為這樣的東西可以安全地工作(將“10”改為grep中的任意數量的行),即使你的文件名中有空格。 根據需要調整。 如果可以使用文件名中的換行符,則需要對其進行調整。

find . -name \*.txt -type f -exec wc -l {} \; | grep -v "^10 .*$" | cut --complement -f 1 -d " " | tr '\012' '\000' | xargs -0 rm -f

這是一個單線選項。 RLINES是用於刪除的行數。

rm \`find $DIR -type f -exec wc -l {} \; | grep "^$RLINES " | awk '{print $2}'\`

問題提出后有點晚了。 我剛才有同樣的問題,這就是Chad Campbell所提出的問題

find $DIR -name '*.txt' -exec wc -l {} \; | grep -v "$LINES" | awk '{print $2}' | xargs rm
  • 第一部分查找以* .txt結尾的DIR中的所有文件並打印行數。
  • 第二部分選擇所有沒有所需行數(LINES)的文件。
  • 第三部分只打印文件名。
  • 第四部分刪除這些文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM