martincarlin87
martincarlin87

Reputation: 11042

Regular Expressions in BASH?

I am ok with regular expressions in Perl but not had to do it in BASH before.

I tried to google for some sort of tutorial on it but didn't see any really good ones yet the way there are with Perl.

What I am trying to achieve is to strip /home/devtestdocs/devtestdocs-repo/ out of a variable called $filename and replace it with another variable called $testdocsdirurl

Hopefully that makes sense and if anybody has any good links that would be much appreciated.

Another way might be is if there is already a function someone has written to do a find and replace in bash.

Upvotes: 3

Views: 489

Answers (6)

The Mask
The Mask

Reputation: 17427

you're looking for an example of how use regular expressions in powershell?

is there an example here:

$input = "hello,123"
$pattern = ([regex]"[0-9]+")
$match = $pattern.match($input)
$ok = $input -match $pattern #return an boolean value if matched..
if($ok) { 
    $output = $match.groups[0].value
    [console]::write($output)
 } else {
   //no match
 }

in 'bash classic' regular expressions usage is precarious. you can use this: http://www.robvanderwoude.com/findstr.php

Upvotes: 0

João Silva
João Silva

Reputation: 91299

sed is the typical weapon of choice for string manipulation in Unix:

echo $filename | sed s/\\/home\\/devtestdocs\\/devtestdocs-repo\\//$testdocsdirurl/

Also, as hop suggests, you can use the @ syntax to avoid escaping the path:

echo $filename | sed s@/home/devtestdocs/devtestdocs-repo/@$testdocsdirurl@

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 246754

With bash

pattern=/home/devtestdocs/devtestdocs-repo/
testdocsdirurl=/tmp/
filename=/foo/bar/home/devtestdocs/devtestdocs-repo/filename
echo ${filename/$pattern/$testdocsdirurl}  # => /foo/bar/tmp/filename

Upvotes: 1

mykhal
mykhal

Reputation: 19895

yes, bash supports regular expressions, e.g.

$ [[ 'abc' =~ (.)(.)(.) ]]
$ echo ${BASH_REMATCH[1]}
a
$ echo ${BASH_REMATCH[2]}
b

but you might rather want to use basename utility

$ f='/some/path/file.ext'
$ echo "/new/path/$(basename $f)"
/new/path/file.ext

excellent source of info is bash manual page

Upvotes: 3

user3850
user3850

Reputation:

Why do you need regular expressions for this?

These are just a few possibilities:

$ filename=/home/devtestdocs/devtestdocs-repo/foo.txt
$ echo ${filename/'/home/devtestdocs/devtestdocs-repo/'/'blah/'}
blah/foo.txt
$ basename $filename
foo.txt
$ realfilename=$(basename "$filename")

Upvotes: 0

DarkDust
DarkDust

Reputation: 92316

You can achieve this without a regular expression:

somepath="/foo/bar/baz"
newprefix="/alpha/beta/"
newpath="$newprefix${somepath##/foo/bar/}"

Upvotes: 3

Related Questions