How can I turn " to " in a bash script

Asked

Viewed 130 times

0

I made a small script in Python that transformed a file .py in a Linux bash script, however, the quotes that are inside the Python file end up making the script not work. Is there any way I can turn them all " of a bash text on \"?

The script I made is this:

#!/bin/bash
pyprog=$(cat $1) # Salva nessa variável o texto do arquivo python

echo "#!/bin/bash
echo \"$pyprog\" | python" > $2

# A saída final desse programa seria algo parecido com:
# !bin bash
# echo "print "Exemplo de um programa em python"" | python
# Assim aspas do comando print vão interferir nas aspas do comando echo 

# Neste caso eu precisaria que o script automaticamente transformasse para
# echo "print \"Exemplo de um programa em python\"" | python
  • Use the backslash \" to rid the " who doesn’t want me to command him echo interpreter.

2 answers

2


write your script as follows:

#!/bin/bash
pyprog=$(cat $1) # Salva nessa variável o texto do arquivo python

echo "#!/bin/bash
echo \"$(echo $pyprog | sed 's/"/\\"/g')\" | python" > $2

The command sed will do the magic of replacing the characters " for \".

In the command this substitution is set with \\" because we need to escape the counter-bar so bash himself doesn’t take things the wrong way.

1

A solution using the command 'tr'

#!/bin/bash

if [ $# -ne 2 ]; then
  echo "erro, precisa de 2 parametros"
  exit 1
fi

tr '"' '\' < $1 | python > $2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.