В текстовом файле, строка которого начинается со строки «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
Дополнительный вход in2:
import { RouterModule } from '@angular/router';
import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import {Test4} from './test4';
@NgModule({
declarations: [AppComponent, NxWelcomeComponent, ScrollDirective, TestComponent, Test4],
})
Ожидаемый результат2:
import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import {Test4} from './test4';
imports: [ScrollDirective, TestComponent, Test4],
awk -f test.awk in2
Почему RouterModule
исчезает из ожидаемого результата?
Вы можете использовать это двухпроходное решение 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
}
/^[[:blank:]]*import/ {
s = $0
gsub(/^[[:blank:]]*import[^{]*{ *| *}.*/, "")
if ($0 in imports) {
print s
pimports[++k] = $0
}
}
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],
Или для второго примера:
awk -f imports.awk in2 in2
import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import {Test4} from './test4';
imports: [ScrollDirective, TestComponent, Test4],
Я добавил дополнительный ввод in2, который получит ожидаемый результат out2.
@anubhava, Спасибо! Не могли бы вы объяснить цель: for (i=1; i<=n; ++i) imports[tok[i]]
Этот цикл проходит через массив tok
, индексированный по позициям 1,2,3...
, в массив imports
, ключи которого будут иметь вид: ScrollDirective,TestComponent,Test4
В качестве альтернативы вы можете использовать Ruby с регулярным выражением и выполнять арифметические операции с массивами из регулярного выражения.
Используя два примера file_1
и file_2
, попробуйте:
$ cat rprog
# read file
inp=$<.read
# create hash of stuff_between_braces=everything up to ;
imports=inp.scan(/^(\s*import\b\s*{\s*([^}\s]+)\s*}[^;]*;)/).map(&:reverse).
to_h
# get declarations and the list that follows
declarations=inp.match(/^\s*declarations:\s*\[([^\]]+)\]/)[1].split(/\s*,\s*/)
# intersection between hash keys and decl list is your goal
(imports.keys & declarations).each{|k| puts imports[k] }
puts "\nimports: [#{(imports.keys & declarations).join(", ")}]\n"
Затем запустите эту программу:
ruby rprog file_1
Распечатки:
import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import { Test2 } from './test2';
imports: [ScrollDirective, TestComponent, Test2]
Или ваш второй пример:
ruby rprog file_2
Распечатки:
import { ScrollDirective } from './directives/scroll.directive';
import { TestComponent } from './test';
import {Test4} from './test4';
imports: [ScrollDirective, TestComponent, Test4]
это единственные строки в ваших входных файлах? есть ли другие строки (не показаны), которые необходимо сохранить, и если да, обновите вопрос, включив в него примеры указанных строк; текущий ответ, хотя и генерирует желаемый результат, будет отбрасывать любые другие строки, которые встречаются во входном файле... из того, что было представлено (пока), неясно, хотите ли вы этого