0

Consider the following bash script

#!/usr/bin/env bash

tstring="Hi\tThere"
istring=$(echo -e $tstring)
echo $istring   # Prints: Hi There
rstring=$(printf '%q' "$istring") # This is not doing what I intended
echo $rstring  # Prints: $'Hi\tThere'

I want rstring to be the same as tstring so that I can test for equality. So basically how do I undo the operation that created istring and get back tstring?

Vikash Balasubramanian
  • 2,921
  • 3
  • 33
  • 74
  • You can't really do that reliably, because once it's converted to the TAB character there's no way to know whether the original escape sequence was `\t` or `\011` or `\x09` or `\u0009`... – Jiří Baum Oct 28 '20 at 08:41
  • ok that makes sense, in that case I will just have to strip out all the spaces so that I can compare them. thanks. – Vikash Balasubramanian Oct 28 '20 at 08:46
  • 1
    `printf "%q" "$string"` converts the `$string` in a format that can be reused as shell input. The form looks like `$'string'` which may include backslash escape sequences. You can mostly retrieve the original string `tstring` by removing leading `$'` and trailing `'`. Please try something like: `rstring=${rstring:2:${#rstring}-3}`. – tshiono Oct 28 '20 at 08:57
  • 1
    Tangentially you actually want `printf -v rstring '%q' "$istring"` – tripleee Oct 28 '20 at 10:08

0 Answers0