过滤文件
Filtering a file
我有一个包含很多行的文件:
at 12:00 the schedule is :
first_task:eating:fruit
second_task:rest:onehour
third_task:watching:horrorfilm
at 18:00 the schedule is :
first_task:eating:vegetals
second_task:rest:threehours
third_task:watching:manga
at 22:00 the schedule is :
first_task:eating:nothing
second_task:rest:sevenhours
third_task:watching:nothing
我在提问之前尝试搜索。但是我没有找到按照我喜欢的方式过滤文件的方法。
我想得到这样的过滤文件:
例如,如果我想知道我今天要吃什么。
at 12:00 eating:fruit
at 18:00 eating:vegetals
at 22:00 eating:nothing
有没有办法使用 awk 或 bash 来做到这一点?
使用awk
,你可以这样做:
awk -F '[\ :]' '/the schedule is/{h=;m=} /eating/{print "at "h":"m" eating:"}' filename
输出:
at 12:00 eating:fruit
at 18:00 eating:vegetals
at 22:00 eating:nothing
这将给出正确答案,即使您将 eating
作为第二或第三个任务。
您可以使用 grep 和 sed 非常简单地完成此操作。假设您的示例文件保存为 f.txt
:
egrep '^at|eating' f.txt | sed 's/first_task://' |
sed 's/the schedule is ://' | paste -d' ' - - | column -t
returns
at 12:00 eating:fruit
at 18:h00 eating:vegetals
at 22:h00 eating:nothing
perl -lne '$a= if(/(^at\s+[^\s]*?)\s/);print $a." ". if(/(eating:.*)$/)'
检查 here 输出。
我有一个包含很多行的文件:
at 12:00 the schedule is :
first_task:eating:fruit
second_task:rest:onehour
third_task:watching:horrorfilm
at 18:00 the schedule is :
first_task:eating:vegetals
second_task:rest:threehours
third_task:watching:manga
at 22:00 the schedule is :
first_task:eating:nothing
second_task:rest:sevenhours
third_task:watching:nothing
我在提问之前尝试搜索。但是我没有找到按照我喜欢的方式过滤文件的方法。
我想得到这样的过滤文件: 例如,如果我想知道我今天要吃什么。
at 12:00 eating:fruit
at 18:00 eating:vegetals
at 22:00 eating:nothing
有没有办法使用 awk 或 bash 来做到这一点?
使用awk
,你可以这样做:
awk -F '[\ :]' '/the schedule is/{h=;m=} /eating/{print "at "h":"m" eating:"}' filename
输出:
at 12:00 eating:fruit
at 18:00 eating:vegetals
at 22:00 eating:nothing
这将给出正确答案,即使您将 eating
作为第二或第三个任务。
您可以使用 grep 和 sed 非常简单地完成此操作。假设您的示例文件保存为 f.txt
:
egrep '^at|eating' f.txt | sed 's/first_task://' |
sed 's/the schedule is ://' | paste -d' ' - - | column -t
returns
at 12:00 eating:fruit
at 18:h00 eating:vegetals
at 22:h00 eating:nothing
perl -lne '$a= if(/(^at\s+[^\s]*?)\s/);print $a." ". if(/(eating:.*)$/)'
检查 here 输出。