Sujay Davalgi
Sujay Davalgi

Reputation: 53

In shell, how to extract substring from a complete file path

If I have the variables like:

baseFolder="/a/b/c/"
completeFilePath="a/b/c/x/y/z.txt"

How to extract the substring from completeFilePath and get the output as:

x/y/z.txt

baseFolder directory depth may be more or less

Upvotes: 3

Views: 4066

Answers (3)

CWLiu
CWLiu

Reputation: 4043

Try to solve this with awk

$ baseFolder="/a/b/c/"
$ completeFilePath="a/b/c/x/y/z.txt"

$ echo $completeFilePath| awk -v a=$baseFolder '{len=length(a)}{print substr($0,len)}'
x/y/z.txt

Brief explanation:

  1. len=length(a): get the length of $baseFolder
  2. substr($0,len): print the substring of $completeFilePath starting from position len

Upvotes: 3

ppp
ppp

Reputation: 1005

You can use bash parameter expansion:

baseFolder="/a/b/c/"
completeFilePath="/a/b/c/x/y/z.txt"

echo "${completeFilePath#$baseFilePath}"

Refer: http://wiki.bash-hackers.org/syntax/pe#substring_removal

Upvotes: 4

l'L'l
l'L'l

Reputation: 47159

Here's a simple way using bash parameter expansion:

b="a/b/c/d/"
p="a/b/c/d/x/y/z.txt"

echo "${p/${b}/}"

The substitution takes the base folder as the pattern and replaces it with nothing (removing it).

Upvotes: 1

Related Questions