S
S
smartlight2012-08-02 12:34:36
linux
smartlight, 2012-08-02 12:34:36

How to extract a word from a string in bash?

Good afternoon habrayudi.
Faced such a problem - it is necessary to select the first word from the end (before the slash) from the string, for example, "/etc/somewhere" into another variable.
How to implement this in bash?

Thanks in advance

Answer the question

In order to leave comments, you need to log in

7 answer(s)
@
@sledopit, 2012-08-02
_

If it is stored in a variable, then:

T=/etc/somewhere ; echo ${T##*/}

If there is a stream from a file, then sed, awk. It is also possible in the while read LINE loop, but this is inefficient (sed and awk together will have time to work out 5-10 times each =) )

R
Ramires, 2012-08-02
@Ramires

Try sed 's|.*/||'
Example:
[email protected]:~$ echo /etc/somewhere | sed 's|.*/||'
somewhere

F
fst, 2012-08-02
@fst

echo /etc/somewhere | grep -E -o '[^/]+$'

D
demimurych, 2012-08-02
@demimurych

[email protected]:~$ basename /etc/crontab
crontab

D
demimurych, 2012-08-02
@demimurych

vvv=`basename /etc/crontab`; echo $vvv;

C
charliez, 2012-08-02
@charliez

echo "/etc/somewhere" | awk -F"/" '{print $3}'

P
Porfel, 2012-08-02
@Porfel

$ foo=/etc/some/where $ bar=${foo##*/} $ echo $bar where $

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question