Abhinav
Abhinav

Reputation: 314

search for a string and after getting result cut that word and store result in variable

I Have a file name abc.lst i ahve stored that in a variable it contain 3 words string among them i want to grep second word and in that i want to cut the word from expdp to .dmp and store that into variable

example:-

REFLIST_OP=/tmp/abc.lst 
cat $REFLIST_OP      
34 /data/abc/GOon/expdp_TEST_P119_*_18112017.dmp       12-JAN-18 04.27.00 AM

Desired Output:-

expdp_TEST_P119_*_18112017.dmp

I Have tried below command :-

     FULL_DMP_NAME=`cat $REFLIST_OP|grep /orabackup|awk '{print $2}'`

     echo $FULL_DMP_NAME

    /data/abc/GOon/expdp_TEST_P119_*_18112017.dmp

Upvotes: 2

Views: 269

Answers (3)

ULick
ULick

Reputation: 999

Using sed with one of these regex

sed -e 's/.*\/\([^[:space:]]*\).*/\1/' abc.lst capture non space characters after /, printing only the captured part.

sed -re 's|.*/([^[:space:]]*).*|\1|' abc.lst Same as above, but using different separator, thus avoiding to escape the /. -r to use unescaped (

sed -e 's|.*/||' -e 's|[[:space:]].*||' abc.lst in two steps, remove up to last /, remove from space to end. (May be easiest to read/understand)

myvar=$(<abc.lst); myvar=${myvar##*/}; myvar=${myvar%% *}; echo $myvar If you want to avoid external command (sed)

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133780

Following awk may help you on same.

awk -F'/| ' '{print $6}'   Input_file

OR

awk -F'/| ' '{print $6}' "$REFLIST_OP"

Explanation: Simply making space and / as a field separator(as per your shown Input_file) and then printing 6th field of the line which is required by OP. To see the field number and field's value you could use following command too:

awk -F'/| ' '{for(i=1;i<=NF;i++){print i,$i}}' "$REFLIST_OP"

Upvotes: 1

Akshay Hegde
Akshay Hegde

Reputation: 16997

REFLIST_OP=/tmp/abc.lst
awk '{n=split($2,arr,/\//); print arr[n]}' "$REFLIST_OP" 

Test Results:

$ REFLIST_OP=/tmp/abc.lst
$ cat "$REFLIST_OP"
34 /data/abc/GOon/expdp_TEST_P119_*_18112017.dmp       12-JAN-18 04.27.00 AM
$ awk '{n=split($2,arr,/\//); print arr[n]}' "$REFLIST_OP" 
expdp_TEST_P119_*_18112017.dmp

To save in variable

myvar=$( awk '{n=split($2,arr,/\//); print arr[n]}' "$REFLIST_OP" )

Upvotes: 1

Related Questions