Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting quotes to pipe separated line using sed

Tags:

bash

sed

I have a custom made tool that parses XML files using SAX and that reproduces them into pipe separated values, an example of a line would be:

name|lastname|address|telephone|age|other info|other info

I would like to rewrite each line, i will do this using a bash script but i'm having some difficulties. Basically i would like to set each word between quotes, an example for the above line would be:

"name"|"lastname"|"address"|"telephone"|"age"|"other info"|"other info"

i'm trying to do this using sed, and i'm partially successful with this sed line

sed 's:|:"|":g'

as i get the output: name"|"lastname"|"address"|"telephone"|"age"|"other info"|"other info

but i dont know how to set quotes for the first char and the last char, Any advice?

like image 388
JBoy Avatar asked Jan 30 '26 07:01

JBoy


1 Answers

You were definitely on the right track, Here's how to cover the special cases of beginning of line, end of line:

 sed 's:|:"|":g;s/^/"/;s/$/"/'

^ char anchors search to beginning of line, the $ char anchors search at the end of the line.

IHTH

like image 139
shellter Avatar answered Feb 01 '26 23:02

shellter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!