Add double quotes around fields in AWK script output?
If you want:
add this to the existing script.
You can insert additional \"\"
in each argument of print
like this:
print "\"admin\"", "\"base\"", ...
Edited:
Yes, perhaps seting OFS is better solution:
BEGIN { OFS="\";\""; } ... print "\"admin", ...., "simple\"";
awk '{for (i=1;i<=NF;i++) $i="\""$i"\""}1' FS=";" OFS=";" input
To add quotes around the entries you could use a simple AWK loop:
Script - simple_loop.awk
BEGIN {FS=";"}
{
for(i=1;i<NF;i++){
printf("\"%s\";", $i);
}
printf("\"%s\"\n",$NF);
}
For instance
echo "admin;base;5.11 HOLSTER SHIRT L WHITE;;" | awk -f simple_loop.awk
Should output
"admin";"base";"5.11 HOLSTER SHIRT L WHITE";"";""
In this case I would use a sed
expression instead of AWK.
If your data is in a file called data.txt
, you can get it writing:
sed "s/;/\";\"/g;s/^/\"/;s/$/\"/" data.txt
That will print the result to the std output, but if you want to replace the content of the file just use sed -i
this way:
sed -i "s/;/\";\"/g;s/^/\"/;s/$/\"/" data.txt
And that is all !!
Explanation:
The sed
expression consists in three sed
commands separated by ";" that you can run separately:
sed "s/;/\";\"/g
It makes a substitution (that is what means the first "s"), then the "/" (the default separator), ";" that is what we want to replace. Then the second separator "/", and the replacement: \";\"
It is a sequence: escaped quote, a semicolon and a escaped quote. So with this command we will replace semicolons ;
by ";"
. The last /g
means that each ;
will be replaced (not only the first smicolon).
If the input was a;b;c
after this running the first command it will be a";"b";"c
.
Now we need to add quotes in the beginning (^
in a regular expression) and in the end ($
). So that is what it means:
sed "s/^/\"/" // the first quote
And
sed "s/$/\"/" // the last quote
Getting the desired output:
"a";"b";"c"