本文介绍了Linux:删除不包含特定行数的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何删除目录中行数比指定行多或少的文件(所有文件均带有".txt"后缀)?
How to remove files inside a directory that have more or less lines than specified (all files have ".txt" suffix)?
推荐答案
此bash脚本应该可以解决问题.另存为"rmlc.sh".
This bash script should do the trick. Save as "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脚本位于当前目录中,则可以防止删除该脚本.
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
这篇关于Linux:删除不包含特定行数的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!