eing9607
asked on
awk string parsing
I have an output that looks like this,
1 2 3 4
5 6 7 8 9 10 11
Now I need to print every string ("1"..."11") plus some extra information. I tried a script like
BEGIN {FS = " "}
{
for (i = 1; i <= NF; i++)
{
if ($i == myvar)
printf("%s %s", $i, mystr)
else
printf("%s ", $i)
if (i == NF)
printf("\n")
}
}
This parses the first string("1") as appearing in column one, but it should appear in column 4, i.e the spaces in columns must be printed.
1 2 3 4
5 6 7 8 9 10 11
Now I need to print every string ("1"..."11") plus some extra information. I tried a script like
BEGIN {FS = " "}
{
for (i = 1; i <= NF; i++)
{
if ($i == myvar)
printf("%s %s", $i, mystr)
else
printf("%s ", $i)
if (i == NF)
printf("\n")
}
}
This parses the first string("1") as appearing in column one, but it should appear in column 4, i.e the spaces in columns must be printed.
ASKER
I haven't included the setting of myvar and mystr here, but I do set them in my awk script.
Well I kind of solved the problem myself. I use the split function, n = ($0, arr, " "), function to retrieve the number of elements on each line. Then I can print each entry stored in arr[1]..arr[n]. By doing so I can (pre)format the output the way I want.
Sorry, when I asked the question I wasn't aware of the split function.
Well I kind of solved the problem myself. I use the split function, n = ($0, arr, " "), function to retrieve the number of elements on each line. Then I can print each entry stored in arr[1]..arr[n]. By doing so I can (pre)format the output the way I want.
Sorry, when I asked the question I wasn't aware of the split function.
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation for this question in the Cleanup topic area as follows:
- PAQ & refund points
Please leave any comments here within the next 7 days
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !
tfewster (I don't work here, I'm just an Expert :-)
I will leave a recommendation for this question in the Cleanup topic area as follows:
- PAQ & refund points
Please leave any comments here within the next 7 days
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !
tfewster (I don't work here, I'm just an Expert :-)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
And how about all the other leading spaces?
Then awk is probably not the rigth choice for that, but can be done too.
Could you please give an example (not phrases) how the output shoul look like.
Also, what does you program do ? the awk-variables myvar and mystr never get set, so they are always the empty string or 0 (depending on the context).