Bash Remove Last Character From String / Line / Word

by on April 26, 2011 · 3 comments· last updated at April 26, 2011

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"
 

See also:



You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 3 comments… read them below or add one }

1 punktyras April 27, 2011 at 2:15 pm

whiile IFS= read -r line

whiile -> while

Reply

2 null May 11, 2011 at 7:55 am

Did you ever heard of “wc -l”? Or “head”/”tail” commands?

Reply

3 Keilaron November 19, 2011 at 8:25 pm

Although a bit rude, the previous comment has a point: You can use head and tail to strip off characters. If you want it to be the first X or last X, you can use -/+, like so:

echo '"foo!"'

“foo!”

echo '"foo!"' | head -c -2

foo!”

echo '"foo!"' | tail -c +2

“foo!

echo '"foo!"' | head -c -2 | tail -c +2

foo!
This is particularly useful with tree -Q (it doesn’t escape properly otherwise).

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , , , ,

Previous Faq:

Next Faq: