how to extract line portion on the basis of start substring and end substring using sed or awk

可紊 提交于 2019-12-24 17:57:41

问题


I have a multiline file with text having no spaces.

Thereisacat;whichisverycute.Thereisadog;whichisverycute.
Thereisacat;whichisverycute.Thereisadog;whichisverycute.

I want to extract string between cat and cute (first occurrence not second) that is the output is

;whichisvery
;whichisvery

I am close to getting it but I end up getting string from cat to the last cute with the command from here.

sed -e 's/.*cat\(.*\)cute.*/\1/'

I am getting

;whichisverycute.Thereisadog;whichisvery
;whichisverycute.Thereisadog;whichisvery

How can I get the text from cat to the first occurrence of cute not last?


回答1:


Given the input you posted all you need is:

$ awk -F'cat|cute' '{print $2}' file
;whichisvery
;whichisvery



回答2:


EDIT: Since I got down vote that I have given solution in awk which I couldn't understand why. So adding a solution in sed(trying if down vote could be removed).

sed 's/cute.*//;s/.*cat//' Input_file

Could you please try following and let me know if this helps you.

awk '{sub(/cute.*/,"");sub(/^.*cat/,"");print}'  Input_file


来源:https://stackoverflow.com/questions/51041463/how-to-extract-line-portion-on-the-basis-of-start-substring-and-end-substring-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!