LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   awk/sed help (https://www.linuxquestions.org/questions/programming-9/awk-sed-help-878355/)

mailvaganam 05-02-2011 10:56 AM

awk/sed help
 
Hi All ,

Need help how do I change following file to below format.
Please advice

Current look
=============
AMBG2K340DR_HBA01 50:01:43:80:07:28:7b:ca
AMBG2K340UAT_HBA01 50:01:43:80:07:28:84:e2
AMBG2K341DR_HBA01 50:01:43:80:07:28:86:26
AMBG2K342DR_HBA01 50:01:43:80:07:28:7b:82

Modify to
===========
"AMBG2K340DR_HBA01","50:01:43:80:07:28:7b:ca"
"AMBG2K340UAT_HBA01","50:01:43:80:07:28:84:e2"
"AMBG2K341DR_HBA01","50:01:43:80:07:28:86:26"
"AMBG2K342DR_HBA01","50:01:43:80:07:28:7b:82"

druuna 05-02-2011 11:04 AM

Hi,

Give this a try:
Code:

sed 's/\(.*\) \(.*\)/"\1","\2"/' infile
Test run:
Code:

cat infile
AMBG2K340DR_HBA01 50:01:43:80:07:28:7b:ca
AMBG2K340UAT_HBA01 50:01:43:80:07:28:84:e2
AMBG2K341DR_HBA01 50:01:43:80:07:28:86:26
AMBG2K342DR_HBA01 50:01:43:80:07:28:7b:82

sed 's/\(.*\) \(.*\)/"\1","\2"/' infile
"AMBG2K340DR_HBA01","50:01:43:80:07:28:7b:ca"
"AMBG2K340UAT_HBA01","50:01:43:80:07:28:84:e2"
"AMBG2K341DR_HBA01","50:01:43:80:07:28:86:26"
"AMBG2K342DR_HBA01","50:01:43:80:07:28:7b:82"


This uses back-referencing: That what is found (all between \( and \) ) in the search part can be represented as \1 (\2 etc) in the replace part.

Here's an on-line sed document: Sed - An Introduction and Tutorial by Bruce Barnett

Hope this helps.

speedy64 05-02-2011 03:35 PM

alternately this works for multiple columns.


Code:

sed 's/^/"/; s/$/"/; s/ /","/'

colucix 05-02-2011 04:47 PM

An awk solution:
Code:

awk 'BEGIN{OFS = ("\"" " " "\"")} $1=$1{print "\"" $0 "\"" }' file

grail 05-02-2011 11:46 PM

Slight change and alternative as my esteemed colleague has overlooked the comma required :)
Code:

awk 'BEGIN{OFS="\",\""}{gsub("^|$","\"")}$1=$1' file

colucix 05-03-2011 12:35 AM

My distinguished colleague is right: I missed that one! :)
Code:

awk 'BEGIN{OFS = "\",\"")} $1=$1 {print "\"" $0 "\"" }' file


All times are GMT -5. The time now is 04:24 PM.