-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.
  • 46,058
  • 19
  • 106
  • 116
Anne K.
  • 345
  • 2
  • 4
  • 7

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
  • 21,411
  • 5
  • 55
  • 102