How do I reverse lines of a file or files under Linux or Unix like operating systems?
You can use any one of the following method.
Say hello to rev command
The rev command copies the specified files, reversing the order of characters in every line. If no files are specified, the standard input (from keyboard) is read. If rev command is installed use it as follows:
echo "nixcraft" | rev
Sample outputs:
tfarcxin
You can use the following syntax too:
rev<<<"This is a test"
Sample outputs:
tset a si sihT
Perl script example to reverse a string
You can use the perl and syntax is:
perl -ne 'chomp;print scalar reverse . "\n";'<<<"nixcraft"
OR
echo 'nixcraft' | perl -ne 'chomp;print scalar reverse . "\n";'
Bash shell script example to reverse a string
You can use bash and sample bash script is:
#!/bin/bash input="$1" reverse="" len=${#input} for (( i=$len-1; i>=0; i-- )) do reverse="$reverse${input:$i:1}" done echo "$reverse"
Run it as follows:
./script nixcraft
Sample outputs:
tfarcxin
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 }
What does ‘<<<' do?
Or what is it?
Python equivalent:
PHP equivalent:
@whyqaz
See Here strings.
Hope this helps!