代码之家  ›  专栏  ›  技术社区  ›  Alexander Mills

删除文件中日期早于x的行

  •  0
  • Alexander Mills  · 技术社区  · 7 年前

    我可以像这样将整个文件读入内存:

    #!/bin/bash
    
    filename='peptides.txt'
    filelines=`cat $filename`
    
    ten_days_ago="$(date)"
    
    for line in $filelines ; do
        date_of="$(echo "$line" | jq -r '.time')"
        if [[ "$ten_days_ago" > "$date_of" ]]; then
           # delete this line
        fi
    done
    

    问题是:

    1. 我可能不想把整个文件读入内存
    2. 如果我用bash一行一行地流式处理它,我如何存储要从中删除的行?我会删除0到x行,其中x行的日期等于10天前。

    二进制搜索在这里是合适的——所以bash可能不是解决这个问题的好方法?我需要找到文件中的行数,除以2,然后转到那一行。

    0 回复  |  直到 7 年前
        1
  •  1
  •   user1934428    7 年前

    仅当文件已排序时,才能使用二进制搜索。

    不需要将整个文件读入内存;您可以逐行处理它:

    while read line
    do
       ....
    done <$filename
    

    而且:是的,我个人不会使用shell脚本来解决这类问题,但这当然是一个品味问题。

        2
  •  1
  •   goose goose    7 年前

    您没有显示输入文件的外观,但从jq及其JSON数据判断。

    话虽如此,我还是会这么做

    today=$(date +%j)
    tenDaysAgo=$(date --date="10 day ago" +%j)
    
    #This is where you would create the data for peptides.txt
    #20 spaces away there is a date stamp so it doesn't distract you
    echo "Peptides stuff                    $today" >> peptides.txt
    
    while read pepStuff; do
        if [ $pepStuff == $tenDaysAgo ]; then
            sed -i "/.*$pepStuff/d" peptides.txt
        fi
    done < <(awk '{print $3}' peptides.txt)