-1

I have a text file that contain a lot of mess text.

I used grep to get all the text that contains the string prod like this

cat textfile | grep "<host>prod*" 

The result

<host>prod-reverse-proxy01</host> <host>prod-reverse-proxy01</host> <host>prod-reverse-proxy01</host> 

Continually, i used sed with the intention to remove all the "host" part

cat textfile | grep "<host>prod*" | sed "s/<host>//g"; "s/</host>//g" 

But only the first "host" was removed.

prod-reverse-proxy01</host> prod-reverse-proxy01</host> prod-reverse-proxy01</host> 

How can i remove the other "/host" part?

5

2 Answers 2

2
sed -n -e "s/^<host>\(.*\)<\/host>/\1/p" textfile 

sed can process your file directly. No need to grep or cat.

-n is there to suppress any lines that do not match. Last 'p' in the script will print all matching files.

Script dissection:

s/.../.../... 

is the search/replace form. The bit between the first and the second '/' is what you search for. The bit between the second and third is what you replace it with. The last part is any commands you want to apply to the replacement.

Search:

^<host>\(.*\)<\/host> 

finds all lines beginning with <host> followed by any text (.*) followed by </host>. Any text between <host> and </host> is stored into internal variable '1' using '(' and ')'. Note that (, ) and / (in </host>) have to be escaped.

Replace:

\1 

Replace found text with contents of variable 1 (1 has to be escaped, otherwise, everything is replaced by character '1'.

Commands:

p 

Print resulting line (after replacement).

Note: Your search involves removing two similar but not identical strings (<host> and </host>).

Sign up to request clarification or add additional context in comments.

1 Comment

Using '/' to delimit various parts of find/replace string is not mandatory. You can use any other character. E.g. sed -n -e "s-^<host>\(.*\)</host>-\1-p" textfile In this case you do not need to escape the '/' inside </host>
0

I think this sed is enough

sed 's/<[/]*host>//g' infile 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.