1

Let's say I have a file with this structure:

1|2|3|4|
5|6|7|8|
9|10|11|12|

However, I want my file to look like this (expected output):

"1"|"2"|"3"|"4"|
"5"|"6"|"7"|"8"|
"9"|"10"|"11"|"12"|

I am trying to used sed command in the following way:

sed 's/^/"/g'

Unfortunately, it only adds quotation marks at the beginning of each line:

"1|2|3|4|
"5|6|7|8|
"9|10|11|12|
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
brenda
  • 656
  • 8
  • 24

3 Answers3

3

^ means "the beginning of a line". Use [^|] instead which means "anything but |". If your implementation of sed supports +, you can use

sed -E 's/[^|]+/"&"/g'

otherwise, you need to be more verbose

sed  's/[^|][^|]*/"&"/g'

& represents the matched part.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
choroba
  • 231,213
  • 25
  • 204
  • 289
2

You can use

sed -E 's/[^|]+/"&"/g' file > newfile

The -E option enables the POSIX ERE syntax and [^|]+ thus matches one or more chars other than |, and "&" replaces each with its copy enclosed with " on both sides.

See the online sed demo:

s='1|2|3|4|
5|6|7|8|
9|10|11|12|'
sed -E 's/[^|]+/"&"/g' <<< "$s"

Output:

"1"|"2"|"3"|"4"|
"5"|"6"|"7"|"8"|
"9"|"10"|"11"|"12"|
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Here is a gnu awk way of doing the same:

awk -v RS="[|\n]+" '{ORS=RT; print "\"" $0 "\""}' file

"1"|"2"|"3"|"4"|
"5"|"6"|"7"|"8"|
"9"|"10"|"11"|"12"|
anubhava
  • 761,203
  • 64
  • 569
  • 643