Reputation: 53
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
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:
len=length(a)
: get the length of $baseFolder
substr($0,len)
: print the substring of $completeFilePath
starting from position len
Upvotes: 3
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
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