如何从字符串数组中获取特定行

时间:2019-01-25 09:23:24

标签: bash shell unix

/server/fmw/idm_111/opatch2019-01-25_08-20-55AM_1.log 
/server/fmw/oamwebgate11g/opatch2019-01-25_08-20-57AM_1.log 
/server/fmw/ohs_111/opatch2019-01-25_08-20-59AM_1.log 
/server/fmw/oracle_common/opatch2019-01-25_08-21-01AM_1.log

上面是外壳中字符串数组的内容,要获取具有ohs_111的行

3 个答案:

答案 0 :(得分:0)

How to check if a string contains a substring in Bash所述,例如:

#!/bin/bash

array=("/server/fmw/idm_111/opatch2019-01-25_08-20-55AM_1.log" 
       "/server/fmw/oamwebgate11g/opatch2019-01-25_08-20-57AM_1.log" 
       "/server/fmw/ohs_111/opatch2019-01-25_08-20-59AM_1.log"
       "/server/fmw/oracle_common/opatch2019-01-25_08-21-01AM_1.log" )

for i in ${!array[*]}
do
  if [[ "${array[$i]}" == *"ohs_111"* ]]
  then
    echo "${array[$i]}"
  fi
done

答案 1 :(得分:0)

请参见以下示例:

#! /usr/bin/env bash
array=("hi...." "..foo/.." "..bar/..")
for i in ${array[@]}; do
    if [[ "$i" =~ "foo" ]] ; then
        echo "$i"
    fi
done

输出:

..foo/..

答案 2 :(得分:0)

grep-打印与图案匹配的行。

例如:

grep -F ohs_111 file_with_content

也可以在脚本中使用grep:

#! /usr/bin/env bash

array=("/server/fmw/idm_111/opatch2019-01-25_08-20-55AM_1.log"
    "/server/fmw/oamwebgate11g/opatch2019-01-25_08-20-57AM_1.log"
    "/server/fmw/ohs_111/opatch2019-01-25_08-20-59AM_1.log"
    "/server/fmw/oracle_common/opatch2019-01-25_08-21-01AM_1.log")

for line in ${array[@]}; do
    grep ohs_111 <<< $line
done

输出:

/server/fmw/ohs_111/opatch2019-01-25_08-20-59AM_1.log