If the quotes are balanced, you will want to remove commas between every other quote, this can be expressed in awk
like this:
awk -F'"' -v OFS='' '{ for (i=2; i<=NF; i+=2) gsub(",", "", $i) } 1' infile
Output:
123,ABC DEV 23,345,534.202,NAME
Explanation
The -F"
makes awk separate the line at the double-quote signs, which means every other field will be the inter-quote text. The for-loop runs gsub
, short for globally substitute, on every other field, replacing comma (","
) with nothing (""
). The 1
at the end invokes the default code-block: { print $0 }
.
sed -e 's/=\([^,]*\)/="\1"/g' file.txt
awk -F, -v OFS=, '{for (f=1;f<=NF;f++) {sub(/=/,"&\"",$f); sub(/$/,"\"",$f)}; print}' file.txt
Or, shorter:
awk -F, -v OFS=, '{for (f=1;f<=NF;f++) {gsub(/=|$/,"&\"",$f)} print}' file.txt
Shorter still:
awk -F, -v OFS=, '{for (f=1;f<=NF;f++) {gsub(/=|$/,"&\"",$f)}} 1' file.txt
Using ex
Ex is designed for file editing, but you can preview changes without actually saving them back to the file like so:
ex -sc '%s/=\([^,]*\)/="\1"/g | %p | q!' file.txt
To actually make the changes and save them to the file, use:
ex -sc '%s/=\([^,]*\)/="\1"/g | x' file.txt
However if you give a pattern which is found nowhere in the file (e.g. there is no =
anywhere in the file) then Ex will not exit automatically. Thus for better robustness I usually use printf
to pass commands to Ex:
printf '%s\n' '%s/=\([^,]*\)/="\1"/g' %p | ex file.txt
And to save changes:
printf '%s\n' '%s/=\([^,]*\)/="\1"/g' x | ex file.txt
Best Answer
To replace single quotes (
'
) it's easiest to put the sed command within double quotes and escape the double quote in the replacement:Note that the single quote is not special within double quotes, so it must not be escaped.
If, instead one wants to replace backticks (
`
), as the question originally mentioned, they can be used as-is within single quotes:Within double quotes, you'd need to escape the backtick with a backslash, since otherwise it starts an old-form command substitution.
See also: