So I have this string:
[email protected]:/home/some/directory/file
I just want to extract the directory address meaning I only want the bit after the ":" character and get:
/home/some/directory/file
thanks.
I need a generic command so the cut command wont work as the $var variable doesn't have a fixed length.
This should do the trick:
$ echo "$var" | awk -F':' '{print $NF}'
/home/some/directory/file
You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:
Parameter Expansion
...
${parameter#word}
Remove Smallest Prefix Pattern.
Theword
is expanded to produce a pattern. The parameter expansion then results inparameter
, with the smallest portion of the prefix matched by the pattern deleted.
In other words, you can write
$var="${var#*:}"
which will remove anything matching *:
from $var
(i.e. everything up to and including the first :
). If you want to match up to the last :
, then you could use ##
in place of #
.
This is all assuming that the part to remove does not contain :
(true for IPv4 addresses, but not for IPv6 addresses)
This might work for you:
echo ${var#*:}
See Example 10-10. Pattern matching in parameter substitution
This will also do.
echo $var | cut -f2 -d":"
awk -F: '{print $2}' <<< $var
For completeness, using cut
cut -d : -f 2 <<< $var
And using only bash:
IFS=: read a b <<< $var ; echo $b
Source: Stackoverflow.com