hot_whisky
hot_whisky

Reputation: 1102

AWK--Print From End of Line till string is found

Using awk or sed, how would one print from the end of a line until (the first instance of) a string was found. For instance, if flow were the string then flow.com would be parsed from www.stackoverflow.com and similarly for www.flow.stackoverflow.com

Upvotes: 0

Views: 951

Answers (3)

Ed Morton
Ed Morton

Reputation: 203674

sed is an excellent tool for simple substitutions on a single line:

sed 's/.*\(flow\)/\1/' file

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246847

GNU grep can do it:

grep -oP 'flow(?!.*flow).*' <<END
www.stackoverflow.com
nothing here
www.flow.stackoverflow.com
END
flow.com
flow.com

That regular expression finds "flow" where, looking ahead, "flow" is not found, and then the rest of the line.

This would also work: simpler regex but more effort:

rev filename | grep -oP '^.*?wolf' | rev

Upvotes: 0

Kent
Kent

Reputation: 195099

try this line if it works for you:

awk -F'flow' 'NF>1{print FS$NF}' file

alternative one-liner:

awk 'sub(/.*flow/,"flow")' file

test (I added some numbers to the EOL, so that we know where did the output come from):

kent$  cat f
www.stackoverflow.com1
and similarly for 2 
www.flow.stackoverflow.com3

kent$  awk -F'flow' 'NF>1{print FS$NF}' f
flow.com1
flow.com3

kent$  awk 'sub(/.*flow/,"flow")' f
flow.com1
flow.com3

note that if the string has some speical meaning (for regex) chars, like *, |, [ ... you may need to escape those.

Upvotes: 1

Related Questions