How can I manipulate a string and then assign it to a variable?

This string manipulation works as I want:

echo ${dir:2:5} | sed 's/[.]$//';


var x = ${dir:2:5} | sed 's/[.]$//';


x = ${dir:2:5} | sed 's/[.]$//';


x = $(${dir:2:5} | sed 's/[.]$//');

all produce errors similar to:

script.sh: line 2: mystring: command not found
script.sh: line 2: x: command not found
script.sh: line 2: var: command not found

My intention is to use this variable in an mv command.

mv /var/$x/test/$x.mp4 /home/me/


x=$(echo "${dir:2:5}" | sed 's/\.$//')
  1. You have to omit the spaces in when you declare a variable (x=value)
  2. $dir is a variable. To print the output of your command you would use echo "${dir:2:5}" | sed 's/\.$//' in the terminal. To save the value in variable x, you replace the value with your command using command substitution $( )
  • Thanks, this is functioning as I expected. The explanation also helps. – user3783243 Apr 25 '19 at 13:53
  • Thanks for the edit! – Freddy Apr 25 '19 at 13:56

Supplement to Freddy's answer; the sed pipe could also be replaced with a bash string substitution. Example:

x=abcd.efghijk ; y="${x:2:5}" ; echo "$y"  "${y/.}"


cd.ef cdef

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.