My text looks like this:
'test' file:
123,James,123,"
hello "X"
this is a "string", cool.
another "string", here.
",7
My goal:
in all lines that doesn't match the pattern [^number,string,number]
or [^",number]
replace
"
with '
.
meaning, the out put should like:
123,James,123,"
hello 'X'
this is a 'string', cool.
another 'string', here.
",7
my sed command so far is:
sed '/\(^[0-9]*,.*,[0-9]*\|^",[0-9]\)/!s/"/'/g' test
my problem is in the substitue part, i'm trying to escape but it doesn't let me, and i can't seems to find a solution to it. if i try to switch '
with #
for example, it works.
I tried : ...!s/"/\'/g'
but it doesn't work.
Would love your help! thanks!
[SOLVED]:
for those who also have this problem, i switched the open paranthese to "
and escaped also the !
the solution:
sed "/\(^[0-9]*,.*,[0-9]*\|^\",[0-9]\)/\!s/\"/'/g"
CodePudding user response:
With your shown samples please try following awk
code. Written and tested in GNU awk
should work in any awk
version.
awk '!/^"/ && !/^[0-9] .*[a-zA-Z] [0-9] /{gsub(/"/,"\047")} 1' Input_file
CodePudding user response:
Using sed
$ sed -E '/^(",)?[0-9] ($|,[[:alpha:]] ,[0-9])/!s/"/'"'"'/g' input_file
123,James,123,"
hello 'X'
this is a 'string', cool.
another 'string', here.
",7
CodePudding user response:
You can use sed -E
so that you don't have to escape the parenthesis.
Note that:
- if you use
[0-9]*
you will match optional digits,[0-9]
matches 1 or more digits. - For the
string
part you use.*
but that matches the whole line
For example
sed -E "/(^[0-9] ,.*,[0-9]|^\",[0-9])/!s/\"/'/g" test
Using awk
and if for example in the first check there can be only 2 comma's:
awk '!/^(",[0-9]|[0-9] ,[^,]*,[0-9])/{gsub(/"/,"\047")}1' test
Both will output:
123,James,123,"
hello 'X'
this is a 'string', cool.
another 'string', here.
",7
CodePudding user response:
This might work for you (GNU sed):
sed -E '/^("|[0-9] ,[^,] ),[0-9] /!y/"/'\''/' file
If the line does not match the required strings then translate all "
's to '
's.
N.B. The idiom '\''
punches a hole into the shell and \'
then quotes the single quote.