I have a variable var
in a Bash script holding a string, like:
echo $var
\"some string.rtf\"
I want to remove the last 4 chara
Hope the below example will help,
echo ${name:0:$((${#name}-10))}
--> ${name:start:len}
start
is the string starting pointlen
is the length of string that has to be removed.Example:
read -p "Enter:" name
echo ${name:0:$((${#name}-10))}
Output:
Enter:Siddharth Murugan
Siddhar
Note: Bash 4.2 added support for negative substring
You can do like this:
#!/bin/bash
v="some string.rtf"
v2=${v::-4}
echo "$v --> $v2"
Using Variable expansion/Substring replacement:
${var/%Pattern/Replacement}
If suffix of var matches Pattern, then substitute Replacement for Pattern.
So you can do:
~$ echo ${var/%????/}
some string
Alternatively,
If you have always the same 4 letters
~$ echo ${var/.rtf/}
some string
If it's always ending in .xyz
:
~$ echo ${var%.*}
some string
You can also use the length of the string:
~$ len=${#var}
~$ echo ${var::len-4}
some string
or simply echo ${var::-4}
To remove four characters from the end of the string use ${var%????}
.
To remove everything after the final .
use ${var%.*}
.