gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:02:30 27 4
gpt4 key购买 nike

如何删除目录中行数多于或少于指定的文件(所有文件都有“.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

关于Linux:删除不包含特定行数的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/935251/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com