In Perl, the chop function removes the last character in a string, but in PHP it removes trailing white spaces only. To get the same functionality into PHP you can use the substr_replace() function. For example:
$string = substr_replace($string,”",-1);
will remove the last character of $string. You can play with it and replace the last character with empty space if you need such a functionality in your script.
Since most of the visits on this page had the ‘Remove last character bash’ search engine keyword, I figured that people might need that section as well, so here it is. To remove the last character from a string/file using bash scripting you need to use the echo option and ‘pipe’ it to the variable itself. For example:
var=”My String with an additional a at the end. a”
var=$(echo ${var%a})
Now, if you do echo $var you will see that it will display “My String with an additional a at the end.” without the additional a at the end :)
People would rather expect to have something that can apply to any last character. Whether it is an a or any other letter.
This code will do it
x=JohnDoee;
echo $x
x=$(echo $x | rev); x=$(echo ${x:1} | rev);
echo $x
Enjoy
On a file you could just run:
sed -n ’s/.$//p’ filename.txt
to print each line in the file without the last character. I don’t see much usage in it though :)
thanks works great
I needed to remove the first character, so I adapted Alan’s code (by the way, thanks Alan!):
x=JJohnDoe;
echo $x
x=$(echo ${x:1});
echo $x
I need to remove several characters from the end of a line, how do I do it? For example, let’s remove two letters from JJohnDoe and leaving JJohnD. Any suggestions?