Monday, April 23, 2012

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?

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
whiile IFS= read -r line
do
echo "${line%?}"
# or put updated line to a new file
#echo "${line%?}" >> /tmp/newfile
done < "/path/to/file"
 

No comments:

Post a Comment