3

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.

3
awk 'BEGIN {
        ...
     }
     # the next line should NOT be within curly braces
     $1 ~ /^Observation/, $1 ~ /^@@@/ { ... }
     {
        ...
     }
     END{
        ...
     }' input.txt > out.csv
  • I edited based on what appears to be the original intent. I may have been wrong though. $1 ~ /^Observation/, /^@@@/ is short for $1 ~ /^Observation/, $0 ~ /^@@@/. – Stéphane Chazelas Sep 1 '15 at 9:56
0

It is unclear what you exactly want to achieve but here is a simplified version that might suit your needs:

awk '
BEGIN { ORS = "$" }
/^N° du cas:/,/^@@@/ {
    sub("N° du cas: ","\n")
    if($1!="@@@")
        print
}
{ next }
END {
    printf("\n")
    printf("Number of records processed : %d",NR)
}'

With you sample input, its output is:

ZX56734562$Blabla$
RF34678432$Blabla$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.