Jonathan Viana
Jonathan Viana

Reputation: 103

Linux sed remove two patterns

I hope you're having a great day,

I want to remove two patterns, I want to remove the parts that contains the word images from a text that I have:

in the files test1 I have this:

APP:Server1:files APP:Server2:images APP:Server3:misc APP:Server4:xml APP:Server5:json APP:Server6:stats APP:Server7:graphs APP:Server8:images-v2

I need to remove APP:Server2:image and APP:Server8:images-v2 ... I want this output:

APP:Server1:files APP:Server3:misc APP:Server4:xml APP:Server5:json APP:Server6:stats APP:Server7:graphs

I'm trying this:

cat test1 | sed 's/ .*images.* / /g'

Upvotes: 0

Views: 49

Answers (3)

Raman Sailopal
Raman Sailopal

Reputation: 12917

GNU aWk alternative:

 awk 'BEGIN { RS="APP:" } $0=="" { next } { split($0,map,":");if (map[2] ~ /images/ ) { next } OFS=RS;printf " %s%s",OFS,$0 }'

Set the record separator to "APP:" and then process the text in between as separate records. If the record is blank, skip to the next record. Split the record into array map based on ":" as the delimiter, then check if there is image in the any of the text in the second index. If there is, skip to the next record, otherwise print along with the record separator.

Upvotes: 0

Michael Discenza
Michael Discenza

Reputation: 1

This should work for you

sed 's/\w{1,}:Server[2|8]:\w{1,} //g'

\w matches word characters (letters, numbers, _) {1,} matches one or more of the preceeding item (\w) [2|8] matches either the number 2 or 8

cat test.file
APP:Server1:files APP:Server2:images APP:Server3:misc APP:Server4:xml APP:Server5:json APP:Server6:stats APP:Server7:graphs APP:Server8:images-v2

The below command removes the matching lines and leaves blanks in their place

tr ' ' '\n' < test.file |sed 's/\w\{1,\}:Server[2|8]:\w\{1,\}.*$//'
APP:Server1:files

APP:Server3:misc
APP:Server4:xml
APP:Server5:json
APP:Server6:stats
APP:Server7:graphs

To remove the blank lines, just add a second option to the sed command, and paste the contents back together

tr ' ' '\n' < test.file |sed 's/\w\{1,\}:Server[2|8]:\w\{1,\}.*$//;/^$/d'|paste -sd ' ' -
APP:Server1:files APP:Server3:misc APP:Server4:xml APP:Server5:json APP:Server6:stats APP:Server7:graphs

Upvotes: 0

Christian Fritz
Christian Fritz

Reputation: 21384

You need to make sure that your wildcards do not allow spaces:

cat data | sed 's/ [^ ]*image[^ ]* / /g'

Upvotes: 1

Related Questions