Bash / Shell-在日期之间插入换行符

问题描述 投票:0回答:2

文件中包含多个日期/时间的数据,依此类推...

示例:

 12/15/19,23:30,80.2
 12/15/19,23:45,80.6
 12/16/19,00:00,80.5
 12/16/19,00:15,80.2

并且想使用一些命令,该命令将自动遍历整个文件,并且在日期更改时,它将插入2个空行,以便我可以在日期更改时更清楚地看到。

我正在寻找该命令后显示的文件的示例:

 12/15/19,23:30,80.2
 12/15/19,23:45,80.6


 12/16/19,00:00,80.5
 12/16/19,00:15,80.2

通过bash / shell命令行命令执行此操作的最佳方法是什么?

bash shell
2个回答
1
投票

使用awk

awk -F',' 'NR>1 && prev!=$1{ print ORS }
{ prev=$1; print }' file
  • 使用,作为字段分隔符
  • 如果不是第一行,并且prev与field1不同,则打印两个换行符(print打印一个换行符,然后输出记录分隔符ORS另外一个)
  • 对于每一行,将字段1的值保存在变量prev中并打印该行

0
投票

由于正在检测多行上的模式,因此您将要使用bash内置而不是grepsed之类的程序。

# initialize variable
last_date=''
# loop over file lines (IFS='' to loop by line instead of word)
while IFS='' read line; do
    # extract date (up to first comma)
    this_date="${line%%,*}"
    # print blank line unless dates are equal
    [[ "$this_date" = "$last_date" ]] || echo
    # remember date for next line
    last_date="$this_date"
    # print 
    printf '%s\n' "$line"
# feed loop with file
done < my_file.txt

这里是较短的复制/粘贴版本:

b='';while IFS='' read l;do a="${l%%,*}";[[ "$a" = "$b" ]]||echo;b="$a";printf '%s\n' "$l";done < my_file.txt

您还可以使其成为函数:

function add_spaces {
    # initialize variable
    last_date=''
    # loop over file lines (IFS='' to loop by line instead of word)
    while IFS='' read line; do
        # extract date (up to first comma)
        this_date="${line%%,*}"
        # print blank line unless dates are equal
        [[ "$this_date" = "$last_date" ]] || echo
        # remember date for next line
        last_date="$this_date"
        # print 
        printf '%s\n' "$line"
    # feed loop with file
    done < "$1"  # $1 is the first argument to the function
}

以便您可以随时调用它:

add_spaces my_file.txt
© www.soinside.com 2019 - 2024. All rights reserved.