Reputation: 553
How can I truncate the ../ or .. characters from string in bash So, If I have strings
str1=../lib
str2=/home/user/../dir1/../dir2/../dir3
then how I can get string without any .. characters in a string like after truncated result should be
str1=lib
str2=/home/user/dir1/dir2/dir3
Please note that I am not interesting in absolute path of string.
Upvotes: 0
Views: 560
Reputation: 881633
You could use:
pax> str3=$(echo $str2 | sed 's?\.\./??g') ; echo $str3
/home/user/dir1/dir2/dir3
Just be aware (as you seem to be) that's a different path to the one you started with.
If you're going to be doing this infrequently, forking an external process to do it is fine. If you want to use it many times per second, such as in a tight loop, the internal bash
commands will be quicker:
pax> str3=${str2//..\/} ; echo $str3
/home/user/dir1/dir2/dir3
This uses bash
pattern substitution as described in the man page (modified slightly to adapt to the question at hand):
${parameter/pattern/string}
The
parameter
is expanded and the longest match ofpattern
against its value is replaced withstring
. If pattern begins with/
, all matches of pattern are replaced with string.If string is null, matches of pattern are deleted and the
/
followingpattern
may be omitted.
Upvotes: 1
Reputation: 77105
You don't really need to fork a sub-shell to call sed
. Use bash
parameter expansion:
echo ${var//..\/}
str1=../lib
str2=/home/user/../dir1/../dir2/../dir3
echo ${str1//..\/} # Outputs lib
echo ${str2//..\/} # Outputs /home/user/dir1/dir2/dir3
Upvotes: 3
Reputation: 3967
You can use sed to achieve it
sed 's/\.\.\///g'
For example
echo $str2 | sed 's/\.\.\///g'
OP => /home/user/dir1/dir2/dir3
Upvotes: 0