У меня этот магазин в переменной
sCellEventTrap-03-28 TRAP-TYPE -- CAC Code: 00 ENTERPRISE compaq VARIABLES { scellNameDateTime, scellSWComponent, scellECode, scellCAC, scellEIP} DESCRIPTION "Severity: Normal -- informational in nature. A physical disk drive has experienced an ID block inconsistency during a periodic drive check." --#TYPE "StorageCell Event" --#SUMMARY "SCellName-TimeDate %s : SWCID %d : ECode: %d : CAC %d : EIP %d." --#ARGUMENTS {0,1,2,3,4,} --#SEVERITY INFORMATIONAL --#TIMEINDEX 136 --#STATE WARNING ::= 13600808Я должен разрезать все до второго появления ". Это дало бы мне:
sCellEventTrap-03-28 TRAP-TYPE -- CAC Code: 00 ENTERPRISE compaq VARIABLES { scellNameDateTime, scellSWComponent, scellECode, scellCAC, scellEIP} DESCRIPTION "Severity: Normal -- informational in nature. A physical disk drive has experienced an ID block inconsistency during a periodic drive check."Другой пример
genericSanEvent TRAP-TYPE ENTERPRISE hpSanManager VARIABLES { severityLevel, category, id, msgString, contactName, contactEmail, contactWorkPhone, contactHomePhone, contactPager, contactFax } DESCRIPTION "A generic SAN event has occurred. The variables are: severityLevel - the event severity level; category - Category of the event being reported; code - ID of the event in the given category; msgString - the message string describing the event; contactName - the name of the individual to be notified of the event; contactEmail - the e-mail address of the individual referred to in contactName; contactWorkPhone - the work phone number of the individual referred to in contactName; contactHomePhone - the home phone number of the individual referred to in contactName; contactPager - the pager number of the individual referred to in contactName; contactFax - the FAX number of the individual referred to in contactName" -- The following are attributes used by xnmloadmib for improved formatting --#TYPE "OV SAM SAN Event" --#SUMMARY "OV SAM SAN Event, Category/Id: %d/%d, Msg: %d Severity: %d Contact: %d" --#ARGUMENTS {1,2,3,0,4} --#SEVERITY CRITICAL --#GENERIC 6 --#CATEGORY "Application Alert Events" --#SOURCE_ID "T" ::= 1Выход для этого примера должен быть:
genericSanEvent TRAP-TYPE ENTERPRISE hpSanManager VARIABLES { severityLevel, category, id, msgString, contactName, contactEmail, contactWorkPhone, contactHomePhone, contactPager, contactFax } DESCRIPTION "A generic SAN event has occurred. The variables are: severityLevel - the event severity level; category - Category of the event being reported; code - ID of the event in the given category; msgString - the message string describing the event; contactName - the name of the individual to be notified of the event; contactEmail - the e-mail address of the individual referred to in contactName; contactWorkPhone - the work phone number of the individual referred to in contactName; contactHomePhone - the home phone number of the individual referred to in contactName; contactPager - the pager number of the individual referred to in contactName; contactFax - the FAX number of the individual referred to in contactName"Использование Perl:
< infile perl -0777 -pe 's/((.*?"){2}).*/$1/s' > outfile
-0777: разворачивает весь файл одновременно вместо одной строки в то время -p: помещает цикл while (<>) {[...]} вокруг скрипта и печатает обработанный file -e: читает скрипт из аргументов Повреждение команды Perl:
-0777: разворачивает весь файл одновременно вместо одной строки в то время [ ! d2] /: запускает паттерн -p: помещает цикл while (<>) {[...]} вокруг скрипта и печатает обработанный файл .*: соответствует любому числу любого символа, ноль или более раз жадно в текущем файле (т. е. он соответствует максимально возможному количеству времени) -e: читает скрипт из аргументов $1: заменяет первую захваченную группу /: останавливает замену строки / запускает модификаторы s: обрабатывает весь файл как одну строку, позволяя . соответствовать также новым строкамХотя многие программы не очень длинны в качестве входных данных, когда ваши данные не огромны, вы часто можете упростить многострочное сопоставление, сначала манипулируя данными, чтобы поместить все в одну строку, выполнив совпадение, а затем восстановив новые строки.
Например, используйте tr для замены newline \n каким-либо символом, который не указан в ваших данных (я использовал возврат-возврат `\ r '), используйте sed для изменения этой отдельной строки, затем tr символ назад :
tr '\n' '\r' < file |
sed 's/\("[^"]*"\).*/\1/' |
( tr '\r' '\n'; echo ) # add a final newline
В противном случае, если вы заявляете, что хотите sed / awk / grep, языки, такие как perl и python, используют аналогичные регулярные выражения, как эти, и подходят для управления многострочными строками. Например, perl:
perl -e '$_ = join("",<>); s/(".*?").*/$1/s; print "$_\n"; ' file
Вот небольшой скрипт python:
#!/usr/bin/env python2
with open('/path/to/file.txt') as f:
print '"'.join(f.read().split('"')[:2]) + '"'
f.read().split('"') прочитает весь файл в виде строки, а затем разделит его на ", чтобы получить все " разделенные части Поскольку нас интересуют только первые две " разделенные части, '"'.join(f.read().split('"')[:2]) присоединяется к первым двум с ". Наконец, мы добавили ", чтобы получить желаемый формат. Вот более короткая версия awk: awk '/TRAP-TYPE/,/[[:alpha:]]*"$/ '
$ awk '/TRAP-TYPE/,/[[:alpha:]]*"$/ ' testfile.txt
sCellEventTrap-03-28 TRAP-TYPE -- CAC Code: 00
ENTERPRISE compaq
VARIABLES { scellNameDateTime,
scellSWComponent,
scellECode,
scellCAC,
scellEIP}
DESCRIPTION
"Severity: Normal -- informational in nature. A physical disk drive has experienced an ID block inconsistency during a periodic drive check."
$ awk '/TRAP-TYPE/,/[[:alpha:]]*"$/ ' testfile2.txt
genericSanEvent TRAP-TYPE
ENTERPRISE hpSanManager
VARIABLES { severityLevel, category, id,
msgString, contactName, contactEmail,
contactWorkPhone, contactHomePhone,
contactPager, contactFax }
DESCRIPTION
"A generic SAN event has occurred. The variables are:
severityLevel - the event severity level;
category - Category of the event being reported;
code - ID of the event in the given category;
msgString - the message string describing
the event;
contactName - the name of the individual
to be notified of the event;
contactEmail - the e-mail address of the
individual referred to in contactName;
contactWorkPhone - the work phone number
of the individual referred to in
contactName;
contactHomePhone - the home phone number
of the individual referred to in
contactName;
contactPager - the pager number of the
individual referred to in contactName;
contactFax - the FAX number of the individual
referred to in contactName"