2

Given a file test.txt, with the content This is a test. I want to extract a substring of its content, more specifically the second and third character ( hi ), using the command

echo ${$(cat test.txt):1:2}

However, this outputs the second and third word ( is a ) instead of the single characters.

I can do

a=$(cat test.txt)
echo ${a:1:2}

And it works as expected. But I want to do it in a single command.

Can someone explain what's happening here and offer a solution?

Edit:

The system is running zsh.

flackbash
  • 488
  • 2
  • 16
  • On my machine (Debian, with bash 4.4) this simply gives a ‘bad substitution’ error. It probably doesn’t officially work. For one thing, you use a $ (substitution) inside the braces in the first expression and not in the second. – Jim Danner Jan 27 '19 at 10:56
  • 1
    You can not do a nested substitution in Bash. https://unix.stackexchange.com/questions/189426/can-command-substitution-be-nested-in-variable-substitution – Shafin Mahmud Jan 27 '19 at 11:00
  • Sorry guys, I overlooked that the system was running zsh instead of bash. – flackbash Jan 27 '19 at 11:51
  • @JimDanner you're right. Apparently zsh is the only shell in which nested substitution is possible, but I still don't understand why my way of doing it results in the observed behavior. – flackbash Jan 27 '19 at 11:57

1 Answers1

0

Can’t explain exactly what is happening there, but you might use sed as an alternative:

sed -E 's/.(..).*/\1/' test.txt

which replaces every line with just its second and third characters.

Jim Danner
  • 535
  • 2
  • 13
  • I am trying to solve a hacking challenge and for this I can't use characters in [;|&`\'"]. That's why I wanted to use the substring expansion command – flackbash Jan 27 '19 at 11:54