Script Shell Extract String

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

researcher

Posted 2016-03-14T16:58:42.017

Reputation: 324

Answers

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/'

Mahmoud Al-Qudsi

Posted 2016-03-14T16:58:42.017

Reputation: 3 274

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.500

Thanks - 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

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'

nex84

Posted 2016-03-14T16:58:42.017

Reputation: 603

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