2

I'm trying to replace a string in a CSV terminated by ~ that it's like a password and I want to escape the delimiter to stop.

I use:

sed -i "s/\(z.*\~\)/\"\1\"/g"

And it's okey but the ~ is not escaped and the regex goes to the final of the line.

Is some way to "stop" the match any character that stops with ~

These are examples of that I have. The second part it's correct because I want to double quote the subexpresion:

zTG*?KM)ии*v=?~~~~~
zTG*?KMии$FhB?~S~~~~

I want to have (or stop)

"zTG*?KM)ии*v=?"~~~~~
"zTG*?KMии$FhB?"~S~~~~

but with de word command at the top I have:

"zTG*?KM)ии*v=?~~~~~"
"zTG*?KMии$FhB?~S~~~~"
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142

3 Answers3

4
$ cat ip.csv 
zTG*?KM)ии*v=?~~~~~
zTG*?KMии$FhB?~S~~~~

$ sed -i 's/z[^~]*/"&"/g' ip.csv 
$ cat ip.csv
"zTG*?KM)ии*v=?"~~~~~
"zTG*?KMии$FhB?"~S~~~~
  • z[^~]* the character z followed by zero or more non ~ characters. Since * is greedy quantifier, it will try to match as many as possible
  • "&" add quotes around matched pattern
  • Note: the g modifier is not needed if there is only single match in a line
Sundeep
  • 23,246
  • 2
  • 28
  • 103
1

@Oriol, Could you please try following and let me know if this helps you.

awk '{sub(/~/,s1"&");sub(/^/,s1);print}' s1="\""  Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • That works, but `awk '{sub(/~/,"\"&"); print "\"" $0}' Input_file` is probably simpler. – mklement0 Jan 10 '17 at 20:03
  • Sorry to answer a bit late, I try this sentence and read the documentation about awk (because I use only sed or egrep) but finally I use Sundeep answer because yours didn't work for me, but thanks anyway. – Oriol Gallart Jan 12 '17 at 07:18
0
echo 'zTG*?KM)ии*v=?~~~~~' | sed -En 's|([^~]+)|"\0"|p'

Result: "zTG*?KM)ии*v=?"~~~~~ It works for me.

Big Shield
  • 612
  • 5
  • 15
  • Note that `\0` only works with _GNU_ `sed`; per POSIX (and with BSD `sed`) you must use `&`. – mklement0 Jan 10 '17 at 19:59
  • Sorry to answer a bit late, I try your sentence and works for me too, but I had used the Sundeep sentence before and it works too. Thanks anyway. – Oriol Gallart Jan 12 '17 at 07:21