-1

I have a string like this

<anytag>my message</anytag>

How I can extract the message between the tags with sed or awk? So I get only "my message"

MOHAMED
  • 35,883
  • 48
  • 140
  • 238

5 Answers5

3

try:

awk -F'[><]' '{print $3}'   Input_file

Making field separator as '[><]' and printing 3rd field.

RavinderSingh13
  • 101,958
  • 9
  • 41
  • 77
1

Using xmllint (from libxml2):

xmllint --xpath '//anytag/text()' <(echo "<anytag>my message</anytag>")
Casimir et Hippolyte
  • 83,228
  • 5
  • 85
  • 113
1
sed 's/<.*>\(.*\)<\/.*>/\1/g' file
tso
  • 4,174
  • 2
  • 17
  • 30
0

I do not want to install xml paser for a lite extract string, my xml message is not complicated

For simple strings you may use the following sed approach:

s="<anytag>my message</anytag>"
sed 's~<[^<>]*>\([^<>]*\)</[^<>]*>~\1~' <<< $s

The output:

my message
RomanPerekhrest
  • 73,078
  • 4
  • 37
  • 76
0

You can use the following awk command if each line of your file is in the format you have shown.

awk -F "<[^<]+?>" '{print $2;}' <filename>

Input:

<anytag>my message</anytag> <mytag>abc</mytag>

Output:

my message
abc
rakinhaider
  • 124
  • 7