Josh
Josh

Reputation: 11

How can I extract part of a string via a shell script?

The string is setup like so:

href="PART I WANT TO EXTRACT">[link]

Upvotes: 1

Views: 9098

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 359935

Here's another way in Bash:

$ string="href="PART I WANT TO EXTRACT">[link]"
$ entity="""
$ string=${string#*${entity}*}
$ string=${string%*${entity}*}
$ echo $string
PART I WANT TO EXTRACT

This illustrates two features: Remove matching prefix/suffix pattern and the use of a variable to hold the pattern (you could use a literal instead).

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342313

use awk

$ echo "href="PART I WANT TO EXTRACT">[link]" | awk -F""" '{print $2}'
PART I WANT TO EXTRACT

Or using shell itself

$ a="href="PART I WANT TO EXTRACT">[link]"
$ a=${a//"/}
$ echo ${a/&*/}
PART I WANT TO EXTRACT

Upvotes: 2

ctd
ctd

Reputation: 1793

grep -o "PART I WANT TO EXTRACT" foo

Edit: "PART I WANT TO EXTRACT" can be a regex, i.e.:

grep -o http://[a-z/.]* foo

Upvotes: 0

ephemient
ephemient

Reputation: 204678

expr "$string" : 'href="\(.*\)">\[link\]'

Upvotes: 0

Related Questions