2

I'm trying to replace all \ with \\ in bash, I'm doing it like this but bash gets stuck in a never-ending loop. Where am I going wrong?

myVar="${myVar//\//\\\\}"
lnogueir
  • 1,859
  • 2
  • 10
  • 21
Radu Bogdan
  • 23
  • 1
  • 3
  • Which version of bash? I can't reproduce an endless loop with this code. – Charles Duffy Apr 19 '21 at 22:15
  • @Barmar, ...insofar as the linked duplicate only provides a sed answer and not a PE answer, it strikes me as suboptimal. – Charles Duffy Apr 19 '21 at 22:16
  • @CharlesDuffy It shows how to do it in a variable, the fact that it's being put into a sed command seems secondary. I tried to find a more general dupe but failed. – Barmar Apr 19 '21 at 22:17
  • Hmm. I _do_ have a working PE-based answer, but I don't think it belongs on the `sed`-centric linked duplicate, and it's distinct from what's already there. – Charles Duffy Apr 19 '21 at 22:17
  • 1
    The answer in my dupe *does* use PE: `${newstring//\\/\\\\}/g` – Barmar Apr 19 '21 at 22:18

1 Answers1

4

You can use sed for that:

echo "hello\world\hello\world" | sed 's/\\/\\\\/g'

Outputs:

hello\\world\\hello\\world
lnogueir
  • 1,859
  • 2
  • 10
  • 21