PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

[FIXED] How to print quotes between value using awk

 August 17, 2022     awk, field, output, separator     No comments   

Issue

I have a file

A|B|C|D|E|F

I need output like

"A","B","C","D","E","F"

I did:

awk -f'|' '{print $1,$2,$3}'

This gives me output just with spaces. My question is how to get comma separated output with quotes, and how to print all values at once without typing '{print $1,$2,$3......}'

I can do:

awk -f'|' '{print """"$1""""","""""$2""""","""""$3""""..}'

But it does not work.


Solution

To specify the field separator, you have to use -F instead of -f; to change what the field separator is for the output, you have to change the OFS variable (the output field separator).

The get quotes around your fields, you can loop over all fields and add them:

$ awk -F"|" -v OFS="," '{for (i=1; i<=NF; ++i){$i="\""$i"\""}}1' infile
"A","B","C","D","E","F"

Alternatively, using sed:

$ sed 's/\([^|]*\)/"\1"/g;y/|/,/' infile
"A","B","C","D","E","F"

This surrounds all sequences of non-pipe characters with quotes, then substitutes all the pipes with commas.



Answered By - Benjamin W.
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing