Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed/awk to remove string from subsections

Tags:

regex

sed

awk

perl

I have a file that looks like this:

bar
barfo
barfoo
barfooo
barfoooo

sample
sampleText1
sampleText2
sampleText3

prefix
prefixFooBar
prefixBarFoo

What I want sed (or awk) to do is to remove the string which introduces a section, from all of its contents, so that I end up with:

bar
fo
foo
fooo
foooo

sample
Text1
Text2
Text3

prefix
FooBar
BarFoo

I tried using

sed -e -i '/([[:alpha:]]+)/,/^$/ s/\1//g' file

But that fails with "Invalid Backreference".

like image 455
Clyybber Avatar asked Dec 05 '22 10:12

Clyybber


2 Answers

$ awk '{$0=substr($0,idx)} !idx{idx=length($0)+1} !NF{idx=0} 1' file
bar
fo
foo
fooo
foooo

sample
Text1
Text2
Text3

prefix
FooBar
BarFoo
like image 102
Ed Morton Avatar answered Dec 08 '22 00:12

Ed Morton


another awk

$ awk '{sub(pre,"")}1; !NF{pre=""} !pre{pre=$1}' file

bar
fo
foo
fooo
foooo

sample
Text1
Text2
Text3

prefix
FooBar
BarFoo
like image 30
karakfa Avatar answered Dec 07 '22 22:12

karakfa