-1

How can I replace a " by \" inside a string using bash?

For example:

A txt-File contains text like:

Banana "hallo" Apple "hey"

This has to be converted into:

Banana \"hallo\" Apple \"hey\"

I tried

a=$(cat test.txt)
b=${a//\"/\"}}

But this didn't work.

How does that work?

Benjamin W.
  • 38,596
  • 16
  • 96
  • 104
Anne K.
  • 275
  • 1
  • 3
  • 6

1 Answers1

1

Use [ parameter expansion ]

string='Banana "hallo" Apple "hey"'
echo "$string"
Banana "hallo" Apple "hey"
string=${string//\"/\\\"} # Note both '\' need '"' need to be escaped.
echo "$string"
Banana \"hallo\" Apple \"hey\"

A lil explanation

${var/pattern/replacement}

replaces one occurrence of pattern in var with replacement.

${var//pattern/replacement}

replaces all occurrences of pattern in var with replacement.

If the pattern or replacement contains characters like " or / with special meaning in shell, they need to be escaped to let shell treat them as literals.

sjsam
  • 20,774
  • 4
  • 49
  • 94