bash-检查字符串是否包含#

时间:2018-07-23 20:41:18

标签: bash shell

我正在尝试在Shell脚本中读取参数文件,并且想跳过以“#”开头的行。已经在Ubuntu VM(默认bash)上尝试过它,对于我不了解的东西,它似乎不起作用。

以下是我正在使用的伪代码:

while read line
do          
    if  [ grep -q "#" <<< "$line" ]; then
        ## Do nothing (Commented Out)           
        echo "$line Line is Commented out"          
    elif [ "$line" = "" ]; then     
        ## Do nothing (Blank Line)          
        echo "Blank line"                       
    else
        #echo "read line is $line"              
        ...some logic here
    fi
done <input_file.ini

这将产生以下错误:Syntax error: redirection unexpected

if [[ $line == *#* ]]构造似乎无效。我以前的经验是在AIX上一切正常。

有人可以引导我在这里做错什么吗?

PS:在相关说明中,我该如何处理不想做任何事情的情况?例如当读取行中没有'#'字符时,我什么也不想做。我不能将if块留为空白,所以我只是使用echo“一些随机”文本。我的任务很好,但只想了解处理此问题的好方法。

2 个答案:

答案 0 :(得分:1)

您的代码显然是使用/bin/sh而不是bash运行的。

[[ $line = *"#"* ]]/bin/sh的替代case

因此,以下将与/bin/sh一起使用,或者与sh yourscript一起调用时:

#!/bin/sh
while read -r line; do : line="$line"
  case $line in
    *"#"*) echo "Line is commented out: $line";;
    "")    echo "Line is empty" ;;
    *)     key=${line%%=*}
           value=${line#*=}
           eval "$key="'$line'  # unsafe, but works with /bin/sh, which doesn't have better
                                # indirect assignment approaches.
           printf '%s\t\t-\t\t%s\n' "$key" "$value"
           ;;
  esac
done <input_file.ini

或者,考虑在使用非bash shell调用脚本时处理一下情况:

#!/bin/bash
case $BASH_VERSION in
  '')
    echo "ERROR: Run with a non-bash shell" >&2
    if [ "$tried_reexec" ]; then
      echo "ERROR: Already attempted reexec and failed" >&2
      exit 1
    fi
    if [ -s "$0" ]; then
      export tried_reexec=1
      exec bash "$0" "$@"
    fi
  ;;
esac

while read -r line; do
  if [[ $line = *"#"* ]]; then
    echo "Line is Commented out: $line"          
  elif [[ "$line" = "" ]]; then
    echo "Blank line"                       
  else
    key=${line%%=*}; value=${line#*=}
    printf -v "$key" %s "$value"
    printf '%s\t\t-\t\t%s\n' "$key" "$value"
  fi
done <input_file.ini

答案 1 :(得分:0)

我真的无法找出双精度[[]]和字符串中的字符搜索的确切问题。感谢所有试图帮助我的人。但这起到了威慑作用,我不想继续摆弄太久,我使用了略有不同的方法来处理我的情况。

以下代码现在对我有效:

while read line
do      
    first_char=`echo $line | cut -c 1`

    if  [ "$first_char" = "#" ]; then           
        : "do nothing here. Line is commented out"
    elif [ "$line" = "" ]; then     
        : "do nothing here. Blank line"                 
    else                
        KEY="$(echo $line | cut -d '=' -f1)"
        VALUE="$(echo $line | cut -d '=' -f2)"
        printf \v "$KEY" %s "$VALUE"

        echo "$KEY\t\t-\t\t$VALUE"
    fi
done < ${SCHEDULER_LOC}/inputs/script_params.ini

我还能学到一些东西,因此也将它们结合在一起。对于这个问题,我确实获得了很少的负面评分。可以理解的是,因为这对于专家来说可能是基本的,但这是一个真正的问题,我正在寻求一些指导。不过,我很感激我学到了一些新东西。对社区表示敬意。