bash:过滤除最新的n条记录

bash:过滤除最新的n条记录

我正在创建一个小脚本,它将删除 Elasticsearch 集群上的索引,以防止它用 Logstash 数据填满所有存储。

我有一个记录列表,我想保留最新的 n 条记录(例如 7 条)并删除所有其他记录。

我可以使用curl 获取索引列表:

drakaris:~/ # curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort
logstash-2022.12.30
logstash-2022.12.31
logstash-2023.01.01
logstash-2023.01.02
logstash-2023.01.03
logstash-2023.01.04
logstash-2023.01.05
logstash-2023.01.06
logstash-2023.01.07
logstash-2023.01.08
logstash-2023.01.09

在我的脚本中,我想仅保留最新的第 7 个索引,并使用“curl -XDELETE localhost: 9200/指数”。

如何从 bash 中的数组中获取这些记录?

谢谢


[编辑]我用这种方式解决了,以防万一有人发现它有用

RETENTION=7
nbk=$(curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | wc -l)
if [ $nbk -gt $RETENTION ]; then
    echo -e "======== Delete obsolete indexes (retention: $RETENTION)"
    let ntodel=$nbk-$RETENTION
    for efile in $(curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort -r | /usr/bin/tail -$ntodel); do
        curl -XDELETE localhost:9200/$efile
        sleep 10
    done
fi

答案1

这应该很简单。试试这个(未经测试!)

drakaris:~/ # curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort | tail -n +8
logstash-2022.12.30
logstash-2022.12.31
logstash-2023.01.01
logstash-2023.01.02

请注意,您可能想在这里使用headtail来获取所需的内容,然后通过管道输入类似为每个端点xargs curl...调用端点之类的内容...DELETE

检查 and 的联机帮助页head并注意命令中tail的使用。+

答案2

您可以将列表映射到 bash 中的数组。使用readarray (或 alias )进行进程替换mapfile,因为管道/子 shell 不会返回变量。

readarray -t indexes < <(curl -sL localhost:9200/_cat/indices/logstash-* | awk '{print $3;}' | sort)

# now iterate the array, except the last 7 entries
# (if the array size is < 7, the loop would not enter)
for (( i=0; i < (${#indexes[*]}-7); i++ )); do 
  # delete unwanted indexes
  curl ... ${indexes[$i]}
done

相关内容