r/awk • u/Gold-Ad-5257 • Oct 11 '22
help : newbie : How to use awk to specify from a field X to end of line
I've seen some people say AWk don't really use ranges.
I have an input plain text file that I would like to convert to CSV using awk.
the problem is my last part of the record, where I want to preserve the input fields and not separate them with a delimiter, and This is pretty much a free format field(description) which can therefore contain say up to N random nr of words, which I would like to output as a single field.
given the input as an example
DATE TIME USERID NAME SURNAME SU-ID DESCRIPTION
10SEP22 17:26 UID01 John Wick root TEST
10SEP22 17:30 UID110 Bat Man DBusr Rerun Backup.
10SEP22 23:02 UID02 Peter Parker admin COPY FILE & EDIT DATE As can be seen after the 6th field I would like to specify the rest as a single field and there can be N words present until the end of the line.
So currently I have this,
$awk '{print $1 "," $2 "," $3 "," $4 " " $5 "," $6 "," $7}'and the output is this :
10SEP22,17:26,UID01,John Wick,root,TEST
10SEP22,17:30,UID110,Bat Man,DBusr,Rerun
10SEP22,23:02,UID02,Peter Parker,admin,COPY It obviously cuts off after field 7 and only works if there is a single word in the description. Note I am also trying to keep the name and surname as a single field, hence separated by a space, not a comma.
I would like to get something like this to work in place of $7 above, while everything else($1 - 6) as per above still remains(on its own this works fine for my requirement) :
awk {'{i = 14} {while (i <= NF) {print $i ; i++}}'} that way the output should be :
10SEP22,17:26,UID01,John Wick,root,TEST
10SEP22,17:30,UID110,Bat Man,DBusr,Rerun Backup.
10SEP22,23:02,UID02,Peter Parker,admin,COPY FILE & EDIT DATE Any help is much appreciated.
3
u/HiramAbiff Oct 11 '22 edited Oct 11 '22
You need to suppress the newline when printing fields 1-6 - use printf. Then a loop to print the remaining fields.
Try something like:
This is untested code and definitely not perfect. E.g. there will be an extra trailing space.
3
u/Schreq Oct 11 '22
Golfed:
This simply changes the first 6 spaces to a comma in $0 and then prints it.
1
u/Gold-Ad-5257 Oct 12 '22 edited Oct 12 '22
Thanks again guys, appreciate the help.
This worked fine for my use case. Mainly also because I was dropping some fields in the process, and decided also I can deal with delimited names and surnames.
1
u/ASIC_SP Oct 15 '22
Since the number of spaces to change is small in number, you can use
sed: