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:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop














{ 3 comments… read them below or add one }
whiile IFS= read -r line
whiile -> while
Did you ever heard of “wc -l”? Or “head”/”tail” commands?
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:
“foo!”
foo!”
“foo!
foo!
This is particularly useful with tree -Q (it doesn’t escape properly otherwise).