简体   繁体   中英

awk processing single line with fields separated by semicolons failing with RS

I have a file called strg.cfg with the content

iMac;1;1;37;;Monitor;1;1;0;;Thunderbolt;1;0;0;;TimeMachine;0;0;0;;USB;1;0;0;;Lacie Stereo;0;0;0;;Rland MacMini;0;0;0;;Scanner;0;0;0;;end

The records are separated by two semicolons ;; and the fields by a single semicolon. I tried to process this file with the following awk file

BEGIN {FS=";"; RS="/\;\;/"}
{ print $1 ", " $2 ", " $3 ", " $6 }

$6 is used as a test since if it works it shouldn't print anything for that since it's only four fields. But that doesn't seem to work, as if the RS= is not taken into consideration at all. It will always still see the whole line as the record. Printing "Monitor" for $6 and not printing other lines.

You don't show the expected output so we're left guessing but is this what you want?

$ cat tst.awk
BEGIN {FS=";"; OFS=", "; RS=";;"}
RT{ print $1, $2, $3, $6 }

$ awk -f tst.awk file
iMac, 1, 1,
Monitor, 1, 1,
Thunderbolt, 1, 0,
TimeMachine, 0, 0,
USB, 1, 0,
Lacie Stereo, 0, 0,
Rland MacMini, 0, 0,
Scanner, 0, 0,

The above uses GNU awk for multi-char RS and RT. If you don't have GNU awk then the simplest solution is to convert the ;; s to the usual RS (\\n) first:

awk '{gsub(/;;/,"\n")}1' file | awk '....'

but if you'd rather avoid the 2 awk calls and pipe then you can do this:

$ cat tst.awk
BEGIN {FS=";"; OFS=", "; RS=";"}
/^$/ {
    $0 = rec
    rec = ""
    print $1, $2, $3, $6
    next
}
{ rec = (rec ? rec FS : "") $0 }

$ awk -f tst.awk file
iMac, 1, 1,
Monitor, 1, 1,
Thunderbolt, 1, 0,
TimeMachine, 0, 0,
USB, 1, 0,
Lacie Stereo, 0, 0,
Rland MacMini, 0, 0,
Scanner, 0, 0,

Awk combines different commands. When you just want to replace ;; by a new line before selecting fields, you can do

sed 's/;;/;\n/g' strg.cfg | cut -d";" -f1,2,3,6

or replace some stuff in the result

sed 's/;;/;\n/g' strg.cfg | cut -d";" -f1,2,3,6 | sed 's/;/, /g'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM