Remove double quotes embracing variable strings from terminal

I have several files that contain this kind of line:

from="$variable_name" and other stuff

$variable name can change, so I could have

from="$myArray" and other stuff
from="$items" and other stuff
from="$list" and other stuff

I need to remove the double quotes that embrace the variable. The result should be

from=$myArray and other stuff
from=$items and other stuff
from=$list and other stuff

This replacement is needed in all files inside a folder.

Is it possible to achieve this with sed and/or awk?

1 Answer

This will do it for the examples you provided:

sed 's/"//g' <your_dir/*

Once you've confirmed it does what you want, just add the -i and remove the<:

sed -i 's/"//g' your_dir/*

However, if there could be a " in the and other stuff part of the line like:

from="$variable_name" and "other" stuff

then you could run 2 substitution commands, one to replace "$ with $ and another to remove the second " like so (doing the replacement in-place):

sed -i 's/"\$/\$/; s/"//' your_dir/*

to get

from=$variable_name and "other" stuff

If you have other lines with double quotes but not of the formfrom="$variable_name"... like this:

from="$myArray" and other stuff
from="$list" and "other" stuff
more "stuff"

then you can do:

sed -i 's/^from="\$/from=\$/; s/\(\$\w\+\)"/\1/' your_dir/*

The ways it's working is as follows:

  • \$\w+ means '$OneOrMoreLetters'
  • I remember this part by enclosing it in between \( and \)
  • Then replace with and the remembered content \1
  • since I didn't put the " inside the memory, it doesn't show up in the replacement.
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like