【问题标题】:Grabing values from one file (via awk) and using them in another (via sed)从一个文件中获取值(通过 awk)并在另一个文件中使用它们(通过 sed)
【发布时间】:2017-10-05 05:57:09
【问题描述】:

我正在使用 gawk 从文件中获取一些值,但不是所有值。我有另一个文件,它是一个模板,我将使用它来替换某些部分,然后生成一个特定于我抓取的那些值的文件。我想使用 sed 替换模板中的这些感兴趣的字段。

  the dog NAME , likes to ACTION in water when he's bored

另一个文件 f1 将包含狗的名称和动作

   Maxs,swim
   StoneCold,digs
   Thor,leaps

所以我可以获取这些值并将它们存储到一个关联数组中...我不能做什么,或者说,我如何将这些值添加到我的 sed 脚本中? 所以一个简单的 sed 脚本可能是这样的

s/NAME/ value from f1
s/ACTION/ value from f1

所以我对模板的输出是

  the dog Maxs , likes to swim in water when he's bored

所以,如果我运行一个 bash 文件,该命令看起来像这样,或者我已经尝试过

    gawk -f f1 animalNameAction | sed -f (is there a way to put something here) template | cat

       gawk -f f1 animalNameAction > PulledValues| sed -f PulledValues template | cat

但这些都没有奏效。所以我想知道如何做到这一点。

【问题讨论】:

    标签: bash awk sed gawk distinct-values


    【解决方案1】:

    你可以这样做,使用 awk 本身,

    我假设,模板可以是多行字符,

    • 所以在FNR==NR{} 块中,我将整个文件(模板)内容保存在变量t 中,
    • 在其他块中,我将NAMEACTION 替换为逗号分隔文件中的第一个和第二个字段。

    这里是示例:

    $ cat template 
    the dog NAME , likes to ACTION in water when he's bored
    
    $ cat file 
    Maxs,swim
    StoneCold,digs
    Thor,leaps
    
    $ awk 'FNR==NR{ t = (t ? t RS :"") $0; next}{ s=t; gsub(/NAME/,$1,s); gsub(/ACTION/,$2,s); print s}' template FS=',' file 
    the dog Maxs , likes to swim in water when he's bored
    the dog StoneCold , likes to digs in water when he's bored
    the dog Thor , likes to leaps in water when he's bored
    

    更好的可读性:

    awk 'FNR==NR{ 
                  t = (t ? t RS :"") $0; 
                  next
         }
         {  
             s=t; 
             gsub(/NAME/,$1,s); 
             gsub(/ACTION/,$2,s); 
             print s
         }
         ' template FS=',' file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多