Sometimes you may need to remove last N characters from string. You can easily do this using shell script. In this article, we will look at how to create shell script to remove last N characters from string.
Shell Script to Remove Last N Characters from String
Here is how to create shell script to remove last N characters from string.
1. Create Shell Script
Open terminal and create empty shell script.
$ sudo vi test.sh
2. Add Shell Script
Add the following code to your shell script file
#!/bin/bash v="test string" n=$1 v2=${v::-$1} echo "$v --> $v2"
In the above code, we accept how many characters need to be removed as command line argument. In line 4, we assign v2 variable to have all characters from string stored in $v except the last N characters.
3. Make Shell Script Executable
Run the following command to make the shell script executable.
$ sudo chmod +x test.sh
4. Test Shell Script
You can run your shell script with the following command. Please note, you need to specify how many characters you want to remove, when you run shell script.
$ sudo ./test.sh 4 test string- -> test st
As you can see out script has removed the last 4 characters from string.
Also read:
How to Find Unused IP Addresses in Network
How to Setup Email Alerts for Root Login
How to Extract IP Address from Server Log
How to Switch User without Password in Ubuntu
How to Find Most Frequent IP Addresses in Apache Log
Related posts:
How to Setup 2 Factor Authentication for SSH in Linux
How to Install Printer in Ubuntu Through Terminal
How to Keep SSH Session Alive After Disconnect in Linux
How to Run MySQL Query from Command Line
How to Use Journalctl Command in Linux
How to Unrar Files with Password in Linux
How to List SFTP Users Who Have Access in Linux
How to Lock & Unlock Users in Linux

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.