LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   My field separator changes when using awk (https://www.linuxquestions.org/questions/programming-9/my-field-separator-changes-when-using-awk-175811/)

Helene 04-29-2004 12:51 AM

My field separator changes when using awk
 
Hi,
I have this file:
Helene;/home/home.html;24/02/04 14:16:09;oldcomment
Helene;/home/home.gif;24/02/04 14:16:09;oldcomment

With this code, I want to change the comment (last field of the record), to a new comment specified by the user.

variable="Helene"
awk -F';' ' { if( $1 ~/'${variable}'/ ){
print "Please enter a comment for this record: " >"/dev/tty"
print $0 > "/dev/tty"
getline newcomment < "/dev/tty"
$5=newcomment
print $0 }
} ' myFile > tmpFile

This is the result:
Helene /home/home.html 24/02/04 14:16:09 newcomment1
Helene /home/home.gif 24/02/04 14:16:09 newcomment1

Where is my field separator going?? :eek:

slakmagik 04-29-2004 09:44 AM

You're declaring the semi-colon as a field separator and only telling it to print fields. So the semi-colon isn't being printed because it's not part of a field. My awk is terrible so I don't know the right way - I think there's an elegant way around this but a stubborn 'I want a semi-colon!' method would be

Code:

variable="Helene"
awk -F';' ' { if( $1 ~/'${variable}'/ ){
        print "Please enter a comment for this record: " >"/dev/tty"
        print $0 > "/dev/tty"
        getline newcomment < "/dev/tty"
        $5=newcomment
        print $1";"$2";"$3";"$5 }
} ' myFile > tmpFile

Something along those lines.

Helene 04-29-2004 08:17 PM

Thanks Digiot. That's the same solution as I came up with my self. It doesn't look very good, but it works!! :) Thanks anyway..

Hko 05-01-2004 08:10 AM

To make it "look better" you should also set an output separator ("OFS"). AFAIK this cannot be done from a command line option, but needs to be set from inside the awk-script. So below the input separator ("FS") is also set inside the script instead of with the -F';' option.
Code:

variable="Helene"
awk 'BEGIN {FS=";" ; OFS=";"} { if( $1 ~/'${variable}'/ ){
print "Please enter a comment for this record: " >"/dev/tty"
print $0 > "/dev/tty"
getline newcomment < "/dev/tty"
$5=newcomment
print $0 }
} ' myFile > tmpFile



All times are GMT -5. The time now is 02:19 AM.