I run the following script under Linux (Mint on a USB key) with GNU Awk 4.0.1 installed by default.
Error returned by awk is the following :
awk: cmd. line:7: /^Observation/,/^@@@/ {sub("/^N° of case: \\(.*\\)$","\\1\\$"); print}
awk: cmd. line:7: ^ syntax error
The script is the following (with "…" replacing some unrelevant code lines that I have removed here) :
#!/bin/bash
...
awk 'BEGIN \
{
FS = "@@@\n"; RS = "###-###\n"; OFS = "$"; ORS = "\n"; SUBSEP = ","
printf("CaseNum$Department$Topic\n");
}
{
# Body awk script
/^Observation/,/^@@@/ {sub("/^N° of case: \\(.*\\)$","\\1\\$"); print}
/^Observation/,/^@@@/ {sub("/^Department: \\(.*\\)$","\\1\\$"); print}
/^Observation/,/^@@@/ {sub("/^Topic: \\(.*\\)$","\\1\\$"); print}
}
END \
{
#printf("Number of records processed : %d",NR);
}' input.txt > out.csv
FYI, the input.txt file which is parsed by the script is like the following (with the "Blabla" that can be anything and have any lenght).
...
Observation
Blabla
N° of case: ZX56734562
Blabla
Department: 56
Blabla
Topic: ER
Blabla
@@@
Blabla
@@@
Blabla
###-###
Observation
Blabla
N° of case: RF34678432
Blabla
Topic: TYG
Blabla
@@@
Blabla
...
Please note that some fields can be missing but the out.csv file must keep any fiels, even those omitted (e.g : here the "Department" field of the second record is missing and the out.csv has a blank case)
And I want to get the following out.csv (csv format with header in 1st line):
CaseNum$Department$Topic
ZX56734562$56$ER
RF34678432$$TYG
I know how to do it with sed but I want to use awk. Moreover, I want to keep my code structure (several lines instead of 1 line condensed code, BEGIN and END blocks, and the two-pattern filter in order to avoid bad fields that could be found in "Blabla").
Thanks in advance.
Best Answer