Bash Remove Last Character From String / Line / Word

I have a file of that looks as follows:

foo bar
tom jerry
UNIX Linux

Each word and/or Linux is a different length. How do strip or remove the last character from each line using bash or ksh shell only on a Linux or Unix-like systems?[donotprint][/donotprint]

You can use any one of the following commands:

  • Bash/ksh shell substitution
  • cut command
  • head command
  • tail command

Bash/ksh shell substitution example

The syntax to remove last character from line or word is as follows:

x="foo bar"
echo "${x%?}"

Sample outputs:

foo ba

The % is bash parameter substitution operators which remove from shortest rear (end) pattern. You can use the bash while loop as follows:

#!/bin/bash
while IFS= read -r line
do
       echo "${line%?}"
       # or put updated line to a new file
       #echo "${line%?}" >> /tmp/newfile
done < "/path/to/file"

cut command example

The syntax is as follows:

## if length of STRING is 3, pass 2 as  character positions 
echo "foo"| cut -c 1-2
## if length of STRING is 14, pass 13 as character positions 
echo "SXI LLC Linux" | cut -c 1-13
See also:

# Additional correction by James K; Editing by VG – log #

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.