Skip to main content

Command Palette

Search for a command to run...

Cut string between two XML nodes using GREP

Published
1 min read
Cut string between two XML nodes using GREP
M

DevOps Engineer | Kubernetes | Python | Terraform | AWS | GCP

Say you want to extract some string between two patterns. GREP's Perl integration does a nice job to perform such match.

For example, the string given is,

<toplevel><suggestion data="hello kitty"/></toplevel>

And you want to extract between toplevel tags. The following GREP command do it nicely.

grep -P -o '(?<=(<tag>)).*(?=(</tag>))'

The whole script is

#!/bin/bash

# STRING = <toplevel><suggestion data="hello kitty"/></toplevel>
# OUTPUT = <suggestion data="hello kitty"/>

RESPONSE_STR='<toplevel><suggestion data="hello kitty"/></toplevel>'

echo "$RESPONSE_STR" | grep -P -o '(?<=(<toplevel>)).*(?=(</toplevel>))'

More from this blog

M

Minhaz's Blog

111 posts