0
#! /bin/sh
lineversion ="/tmp/g-9.n.gggg1000.fr-worker1.V.2.tar.bz2"
My question: how can i extract
g-9.n.gggg1000.fr-worker1.V.2
from
$lineversion
in another variable
0
#! /bin/sh
lineversion ="/tmp/g-9.n.gggg1000.fr-worker1.V.2.tar.bz2"
My question: how can i extract
g-9.n.gggg1000.fr-worker1.V.2
from
$lineversion
in another variable
2
newvar=`echo $lineversion | sed 's/\.tar\.bz2//' | sed 's/\/tmp\///'`
sed
is unix's "search and replace" utility. In the above example, we are searching for first ".tar.bz2" (and escaping the dots with a preceding backslash) and replacing it with nothing, and then taking that output and searching for "/tmp/" and replacing it with nothing similarly.
In general: sed 's/search_for/replace_with/'
2
You can use the substring syntax to extract characters from fixed position :
echo ${lineversion:position:length}
echo ${lineversion:5:30}
Another method would be to cut a little bit of not needed characters :
echo ${lineversion} | cut -d '/' -f3 | sed 's/\.tar\.bz2$//g'
1Nice answer, +1 from me! You have a typo in your initial example (no colon preceding the position) – Mahmoud Al-Qudsi – 2016-03-14T17:07:11.693
You can save time and ressources by doing only one sed command ( and avoid double pipe) : newvar=
echo $lineversion | sed -e 's/\.tar\.bz2//' -e sed 's/\/tmp\///'
. Plus, you missed the backquotes (`) around your command to set it into your variable. – nex84 – 2016-03-14T17:15:33.500Thanks - fixed! I gave up on memorizing sed's parameters because unlike grep, it's too different across Mac/Linux/BSD for me to keep straight (and I use all three). – Mahmoud Al-Qudsi – 2016-03-14T17:27:48.617