如何获取声明行中方括号[]内的字符串及其相关的导入字符串

问题描述 投票:0回答:1

在以“declarations:”字符串开头的行的文本文件中, 将“声明”替换为“进口”, 将“AppComponent”或“NxWelcomeComponent”替换为“”, 解析结果字符串以获取以逗号“,”分隔的单个字符串, 并从上面获取它们相关的导入字符串。 例如 在:

import { RouterModule } from '@angular/router';
import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import { Test2 } from './test2';
import { Test3 } from './test';

@NgModule({
  declarations: [AppComponent, NxWelcomeComponent, ScrollDirective, TestComponent, Test2],
})

预期结果:

import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import { Test2 } from './test2';

imports: [ScrollDirective, TestComponent, Test2],

我尝试过: 测试.awk:

/declarations:/ {str=$0;  sub("declarations", "imports", str) ; sub("AppComponent,", "", str) ; sub("NxWelcomeComponent,", "", str) }
/import/ { importbuf[++arrindex]=$0}

END {
    for (i in importbuf) {
        print importbuf[i]
    }
    print str
}
awk -f test.awk in

awk
1个回答
0
投票

您可以使用这个 2 遍 awk 解决方案。

cat imports.awk

NR == FNR {
   if ($1 ~ /^declarations/) {
      gsub(/[[:blank:]]*declarations[^[[]*\[|].*/, "")
      n = split($0, tok, /[[:blank:]]*,[[:blank:]]*/)
      for (i=1; i<=n; ++i)
         imports[tok[i]]
   }
   next
}
$3 in imports {
   print
   pimports[++k] = $3
}

END {
   printf "\nimports: ["
   for (i=1; i<=k; ++i)
      printf "%s", (i>1 ? ", " : "") pimports[i]
   print "],"
}

然后将其用作:

awk -f imports.awk in in

import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import { Test2 } from './test2';

imports: [ScrollDirective, TestComponent, Test2],
© www.soinside.com 2019 - 2024. All rights reserved.