有没有办法将变量从另一个文件循环到我的bash脚本中?

时间:2015-11-13 16:11:28

标签: bash

很抱歉很痛苦,但我不确定如何将外部文件中的值循环到我的bash脚本中作为变量。我的bash脚本中有三个变量名称:

$TAGBEGIN
$TAGEND
$MYCODE

在一个单独的varSrc.txt文件中,我有几个变量:

@ a - Some marker
tagBegin_a='/<!-- Begin A -->/'
tagEnd_a='/<!-- End A -->/'
code_a=' [ some code to replace in between tags ] '

@ b - Some marker
tagBegin_b='/<!-- Begin B -->/'
tagEnd_b='/<!-- End B -->/'
code_b=' [ some code to replace in between tags ] '

@ c - Some marker
...

我需要我的bash脚本能够遍历每个&#34; @ marker&#34; *部分并执行一个功能:

source varSrc.txt

$TAGBEGIN
$TAGEND
$MYCODE
...
sed '           
    '"$TAGEND"' R '"$MYCODE"'
    '"$TAGBEGIN"','"$TAGEND"' d
' -i $TARGETDIR

注意:sed代码逻辑(不引用混乱)由Glenn J提供。

我需要某种循环逻辑,如:

for (var i = 0; i <= markers in varSrc.txt ; i++) {
// set bash vars equal to varSrc values
$TAGBEGIN=  $tagBegin_i 
$TAGEND= $tagEnd_i
$MYCODE= $code_i

// run the 'sed' replace command
    sed '           
        '"$TAGEND"' R '"$MYCODE"'
        '"$TAGBEGIN"','"$TAGEND"' d
    ' -i $TARGETDIR

}

这是否可以在bash脚本中完成,这是一个好方法吗?非常非常感谢任何建议,指示或指导!

*(我认为这不是我能用的真正标记)

3 个答案:

答案 0 :(得分:2)

[回答原文,修正前的问题]

仅当输入文件是有效的bash语法时,

$stmt = $pdo->prepare(" SELECT* FROM t1 WHERE bus_name = :busName "); $stmt->bindValue(':busName', $busName); $stmt->execute(); var_dump($stmt->fetchAll()); 才有效;它不是。因此,您需要自己解析它,如下所示:

source

答案 1 :(得分:2)

[回答经修正的问题]

根本不需要使用,迭代或考虑标记。把它们留下来。

source varSrc.txt
for beginVar in "${!tagBegin_@}"; do  # Iterate over defined begin variable names
  endVar=tagEnd_${var#tagBegin_}      # Generate the name of the end variable
  codeVar=code_${var#tagBegin_}       # Generate the name of the code variable
  begin=${!beginVar}                  # Look up the contents of the begin variable
  end=${!endVar}                      # Look up the contents of the end variable
  code=${!codeVar}                    # Look up the contents of the code variable

  sed -e "$end R $code" -e "$begin,$end d" -i "$file"
done

答案 2 :(得分:0)

您可以做的是在第二个文件中导出变量,在当前环境中执行脚本(脚本前面有一个点),以获取可以解析文件的变量名称/标记并搜索$或@