Need help to read rows from one file and concatenate to another

Hi guys;

TBH I am an absolute novice, when it comes to scripting; I do have an idea of the basic commands...

Here is my problem;

I have a flatfile 'A' containing a single column with multiple rows. I have to create a script which will use 'A' as input and then output a string in in the format ('row1','row2','row3')
eg:
file A:
Y781
TGH8
UIP9

output:
('Y781','TGH8','UIP9')

NB: No, I'm not a college student asking for help on his coding assignment!

You can do something like that :

awk -v Q="'" '
BEGIN {
   ORS = "";
   print "(";
}
{
   print (NR>1 ? "," : "") Q $0 Q;
}
END {
   print ")\n";
}' inputfile

Inputfile:

Y781
TGH8
UIP9

Output:

('Y781','TGH8','UIP9')

Jean-Pierre.

1 Like
awk 'BEGIN {printf("(");}
       {printf"("'%s'," )  }
       END {printf(")\n") } ' inputfile > outputfile

See how that does for you

1 Like

Jim, there is a problem with your script

$ awk 'BEGIN {printf("(");}
>        {printf"("'%s'," )  }
>        END {printf(")\n") } ' 
 awk: The string  )  } cannot contain a newline character.
 The source line is 2.
 The error context is
                       {printf"("%s," )  } >>> 
 <<< 
 syntax error The source line is 3.
 awk: The statement cannot be correctly parsed.
 The source line is 3.
        awk: There is a missing } character.

and the argument of the printf is missing after the format string.

Another problem is that there will be an unwanted comma before the ) in the resulting output.

Jean-Pierre.

Yeah, the script does have a problem as mentioned by Jean-Pierre in the below post... but thank you for trying to solve my problem!

Hi

awk '$0=q $0 q' q="'" infile | paste -s -d, | sed 's/.*/(&)/'

Guru.

# cat infile
Y781
TGH8
UIP9
# echo "('"$(sed -n "N;N;s/\n/','/gp" infile )"')"
('Y781','TGH8','UIP9')