Bash shell script to reverse text file contain using Shell array

by on April 9, 2008 · 6 comments

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

  1. #!/bin/bash
  2. # Bash shell script to reverse text file contain i.e. concatenate files and
  3. # print on the standard output in reverse. This script also demonstrate how
  4. # to use arrays under bash shell script.
  5. # -------------------------------------------------------------------------
  6. # Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
  7. # This script is licensed under GNU GPL version 2.0 or above
  8. # -------------------------------------------------------------------------
  9. # This script is part of nixCraft shell script collection (NSSC)
  10. # Visit http://bash.cyberciti.biz/ for more information.
  11. # -------------------------------------------------------------------------
  12. FILE="$1"
  13. if [ $# -eq 0 ]; then
  14. echo "$(basename $0) - file-name"
  15. exit 1
  16. fi
  17.  
  18. textArray[0]="" # hold text
  19. c=0 # counter
  20. # read whole file in loop
  21. while read line
  22. do
  23. textArray[$c]=$line # store line
  24. c=$(expr $c + 1) # increase counter by 1
  25. done < $FILE
  26. # get length of array
  27. len=$(expr $c - 1 )
  28.  
  29. # use for loop to reverse the array
  30. for (( i=$len; i>=0; i-- ));
  31. do
  32. echo ${textArray[$i]}
  33. done


4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

  • zakko

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

  • vivek

    zakko,

    Thanks for the heads up.

  • Shane Menshik

    can’t you just do a

    tac filename.txt > filename-reversed.txt

  • snickers

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

  • Anonymous

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

  • Minakshi Kalita

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

Previous Script:

Next Script: