【问题标题】:awk error with indice when used in a loop在循环中使用时带有索引的 awk 错误
【发布时间】:2012-03-24 01:52:16
【问题描述】:

我有以下情况。

 awk '$0 != "Force for tool binder"   # print all lines until string found
 $0 =="Force for tool binder"{
 print ; getline ; print;            # go to 2 lines below the string
 getline; getline < " forceState$j.k "; print}' dynaFile_Offen1.k > tempDynaFile.k   # take the string from 
 #the file forceStates$j.k and replace in the main file, generating a temp file.

问题是这里的 j 是一个循环索引,这意味着对于第一种情况它是 j=1。 当我将它用作 forceStates1.k 时,它工作得很好,但在循环中它没有取值。

我很乐意接受这些建议。

【问题讨论】:

  • @kev 这是一个逻辑错误,而不是语法错误。我的意思是说,它对这个命令没有任何作用。

标签: linux parsing loops indices


【解决方案1】:

$j 中的 '... " forceState$j.k " ...' 不会被展开。
有问题吗?

【讨论】:

  • @kev 是的,我认为它没有得到扩展。
  • 那么在这种情况下该怎么办?我每次都必须从新的 forceStates$j.k
  • 您可以使用-v j=$j 选项将变量传递给awk。并将"forceState$j.k" 更改为"forceState" j ".k"
【解决方案2】:

$j 看起来是一个 shell 脚本变量。由于您的 awk 脚本位于单引号部分中,因此 shell 不会替换 awk 脚本中的变量。所以 awk 看到的是文字 $j。您需要更改 shell 引用以允许替换,或者可能更有用地将其在命令行中传递,例如:

awk -v loopctr=$j 'BEGIN {print loopctr}'

每次都将打印您的循环计数器,因为 j 的值在此处传递到 awk 变量 loopctr 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2017-10-30
    • 2020-11-07
    相关资源
    最近更新 更多