0

I am trying to create a bash script that uses the sed command to replace a pattern by a variable that contains a string or put a space if there is nothing in the variable. I cannot find the good way to write it and make it work. Here is the part where I have issues:

a_flag=$(echo $a | wc -w)

if  [[ $a_flag = 0 ]]; then
    sed -i -e 's/#b/\\hspace{2cm}/g' source.tex
else
    sed -i -e "s/#b/$a/g" source.tex
fi

When running this, the condition is always false. I tried [] or (()) for the if statement but I just can't find a way to fix it.

gdlmx
  • 6,479
  • 1
  • 21
  • 39
  • 1
    Possible duplicate of [Comparing numbers in Bash](https://stackoverflow.com/questions/18668556/comparing-numbers-in-bash) – Wiktor Stribiżew Feb 27 '19 at 13:43
  • Replace your if statement by if [[ "$a_flag" -eq "0" ]]; – nissim abehcera Feb 27 '19 at 13:49
  • @WiktorStribiżew I tried the two solutions of the accepted answer and it still doesn't work. I tried (( a_flag = 0)) and [ "$a_flag" -eq "0"] – temnyles Feb 27 '19 at 14:03
  • `sed -i -e "s/#b/${a:-\\\\hspace{2cm}/g" source.tex`. Done. – chepner Feb 27 '19 at 14:21
  • We are slightly in the dark here because it's unclear what exactly `$a` contains. I guess it's never completely empty, like @chepner assumes. – tripleee Feb 27 '19 at 14:49
  • When `a` is empty, `a_flag` is not the literal string `0`; it's a `0` with a lot of leading whitespace. Use `-eq` to test numerically. – chepner Feb 27 '19 at 15:01

2 Answers2

1

You only need a single parameter expansion here, to replace the expansion of $a with \hspace{2cm} if the expansion is empty.

sed -i -e "s/#b/${a:-\\\\hspace{2cm}}/g" source.tex

You need a stack of \ because there are two rounds of escaping involved. First, the shell itself reduces each \\ to a single literal backslash. Then sed also reduces each pair of \\ to a single literal backslash.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

Counting the number of occurrences of someething seems like a very roundabout way to approach this anyway.

case $a in
   *[A-Za-z0-9_]*) x='\\hspace{2cm}';;
   *)              x=$a;;
esac
sed -i "s/#b/$x/g" source.tex
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • I tried this and this time it prints the \hspace but not the content of a: `case $a in *[A-Za-z0-9_]*) sed -i -e 's/#b/\\hspace{2cm}/g' source.tex;; *) sed -i -e "s/#b/$a/g" source.tex;; esac` – temnyles Feb 27 '19 at 14:22