搜索字符串并在获得结果后切换该字并将结果存储在变量中

时间:2018-01-15 10:08:40

标签: linux unix awk sed grep

我有一个文件名abc.lst我存储在一个变量中它包含3个单词字符串其中我想grep第二个单词,并且我希望将单词从expdp剪切为.dmp并将其存储到变量中

示例: -

expdp_TEST_P119_*_18112017.dmp

所需的输出: -

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

     echo $FULL_DMP_NAME

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

我尝试过以下命令: -

{{1}}

3 个答案:

答案 0 :(得分:1)

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

测试结果:

$ 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

保存在变量

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

答案 1 :(得分:1)

关注awk可能对您有帮助。

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

OR

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

说明: 只需将空格和/作为字段分隔符(根据您显示的Input_file),然后打印所需行的第6个字段通过OP。 要查看字段编号和字段值,您也可以使用以下命令:

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

答案 2 :(得分:0)

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)