Bash shell script to reverse text file contain using Shell array

This script also demonstrate how to use arrays under bash shell script.

#!/bin/bash
# Bash shell script to reverse text file contain i.e. concatenate files and
# print on the standard output in reverse. This script also demonstrate how 
# to use arrays under bash shell script.
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
FILE="$1"
if [ $# -eq 0 ]; then
  echo "$(basename $0) - file-name"
  exit 1
fi
 
textArray[0]="" # hold text
c=0 # counter 
# read whole file in loop
while read line
do
  textArray[$c]=$line # store line
  c=$(expr $c + 1) # increase counter by 1
done < $FILE
# get length of array 
len=$(expr $c - 1 )
 
# use for loop to reverse the array
for (( i=$len; i>=0; i-- ));
do
  echo ${textArray[$i]}
done
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
Category List of Unix and Linux commands
File Management cat
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN Alpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
6 comments… add one
  • Minakshi Kalita May 10, 2011 @ 5:47

    Thanks…………….. But i want this program using switch case

  • Anonymous Jan 4, 2011 @ 0:44

    tac $File | rev
    reverses output of everything, simple, both tac and rev in coreutils

  • snickers Nov 13, 2010 @ 22:52

    It just reverses the ordering of the file lines. It does not reverse the actual text.

  • Shane Menshik Nov 12, 2009 @ 21:51

    can’t you just do a

    tac filename.txt > filename-reversed.txt

  • vivek Jul 24, 2008 @ 7:07

    zakko,

    Thanks for the heads up.

  • zakko Jul 23, 2008 @ 22:54

    textArray[c]=$line # store line
    isn’t it
    textArray[$c]=$line # store line
    ^
    |
    ERROR

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.