elcharrua
elcharrua

Reputation: 1682

Bash replace string

I'm working on a script which checks if file exists. If it exists then I want to get the route.

What I did is the following:

RESULT_=$(find $PWD -name someRandom.json)

This returns the path to the file:

/Users/guest/workspace/random_repo/random/some_folder/someRandom.json

I'm stuck in the way to navigate among files. Is there a way of replacing someRandom.json with '' so I can do:

cd /Users/guest/workspace/random_repo/random/some_folder/

I tried using the solution provided here but it isn't working. I tried the following:

RESULT=$($RESULT/someRandom.json/'')
echo $RESULT

And this returns no such file or directory.

Upvotes: 1

Views: 257

Answers (2)

dawg
dawg

Reputation: 104102

given:

$ echo "$result"
/Users/guest/workspace/random_repo/random/some_folder/someRandom.json

You can get the file name:

$ basename "$result"
someRandom.json

Or the path:

$ dirname "$result"
/Users/guest/workspace/random_repo/random/some_folder

Or you can use substring deletion:

$ echo "${result%/*}"
/Users/guest/workspace/random_repo/random/some_folder

Or, given the file name and the full path, just remove the file name:

$ echo "$tgt"
someRandom.json
$ echo "${result%"$tgt"}"
/Users/guest/workspace/random_repo/random/some_folder/

There are many examples of Bash string manipulation:

BashFAQ/100

BashFAQ/073

Bash Hacker's Parameter Expansion

Side note: Avoid using CAPITAL_NAMES for Bash variables. They are reserved for Bash use by convention...

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

You want parameter expansion, not command substitution.

RESULT="${RESULT%/*}/"

Upvotes: 2

Related Questions