【问题标题】:How to read user defined dictionary using shell scripts?如何使用 shell 脚本读取用户定义的字典?
【发布时间】:2013-04-05 10:23:06
【问题描述】:

假设我有一个BCFile,其内容如下:

inlet
{
    type            fixedValue;
    value           uniform (5 0 0);
}
outlet
{
    type            inletOutlet;
    inletValue      $internalField;
    value           $internalField;
}
....
blahblahblah (other boundary condition with the same dictionary format as above)

为了打印出outlet边界条件的类型,也就是inletOutlet,我以为可以用,

cat BCFile | grep "type" | awk '{printf $2}'  | tr -d ";"

但现在的问题是在使用grep 时出现了很多type 关键字。那么有没有办法先检测到outlet这个词,然后搜索和grep{}之间的内容呢?谢谢!

【问题讨论】:

    标签: shell grep


    【解决方案1】:

    AWK 非常强大。例如,如果您将记录分隔符设置为},则每个块都将成为自己的记录。然后你只需打印匹配的记录:

    $ awk -v RS='}' '/outlet/ { print $0 }' file
    outlet
    {
        type            inletOutlet;
        inletValue      $internalField;
        value           $internalField;
    

    【讨论】:

    • 但是如果是inlet,因为关键字inlet出现了很多次。这种方法将不再起作用。 :(
    • 方法不止一种:可以将匹配条件从/outlet/更改为/inlet\n{/,或$1 ~ /inlet/,或/^inlet/
    【解决方案2】:

    怎么样 grep -A 5 'outlet' BCFile | grep 'type' | awk '{printf $2}' | tr -d ";"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      相关资源
      最近更新 更多