文件中包含多个日期/时间的数据,依此类推...
示例:
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命令行命令执行此操作的最佳方法是什么?
使用awk
:
awk -F',' 'NR>1 && prev!=$1{ print ORS }
{ prev=$1; print }' file
,
作为字段分隔符prev
与field1不同,则打印两个换行符(print
打印一个换行符,然后输出记录分隔符ORS
另外一个)prev
中并打印该行由于正在检测多行上的模式,因此您将要使用bash
内置而不是grep
或sed
之类的程序。
# 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