Reputation: 2585
I have the following text in a file, and I would like to find the word fox
and would like to delete the text before the word fox
from the begining of the text. (including fox)
I want to keep the whole text if there is no match.
The quick
brown fox
jumps over
the lazy dog
The requested outcome will be:
jumps over
the lazy dog
The tool to be used is not important, but I'm with Msys on Windows, and not all the fancy tools are implemented here.
Things I tried:
var=$(echo "${raw}" | awk "/replaceme/{i++}i")
var=$(echo "${raw}" | sed -n "/replaceme/,${p}")
var=$(echo "${raw}" | sed -r -n -e "/replaceme/,${p}")
var=$(echo "${raw}" | sed "/replaceme/,$!d")
Thanks
Upvotes: 1
Views: 80
Reputation: 785196
You can do this easily in awk
:
awk -v s="fox" '$0~s{re="^.*" s "[[:space:]]*"; sub(re, ""); }1' RS= file
jumps over
the lazy dog
When pattern is not found:
awk -v s="box" '$0~s{re="^.*" s "[[:space:]]*"; sub(re, ""); }1' RS= file
The quick
brown fox
jumps over
the lazy dog
EDIT: If you want to delete the text AFTER the match (including the line of match):
awk -v s="over" '$0~s{re="\n[^\n]*" s ".*$"; sub(re, ""); }1' RS= file
The quick
brown fox
Upvotes: 2
Reputation: 75488
If it's only up to the first occurrence of fox
you can have:
sed '1,/fox/d' file
Add -i
as an option if you want to modify the file.
To delete lines up to the last occurrence:
awk 'BEGIN{start=1}{a[NR]=$0}/fox/{start=NR+1}END{for(i=start;i<=NR;++i)print a[i]}' file
To modify:
awk 'BEGIN{start=1;file=ARGV[1]}{a[NR]=$0}/fox/{start=NR+1}END{printf("")>file;for(i=start;i<=NR;++i)print a[i]}>file' file
Upvotes: 0
Reputation: 4106
You can go down the regex path with /^.*fox(.+)|.+/s
.
This way, it will take everything from the text after the last occurence of fox
and, if none found, everything.
Upvotes: 0