Shell Script To Write Odd and Even Line To Respective Files

by on September 17, 2008 · 1 comment

  1. #!/bin/bash
  2. # Write a shell script that, given a file name as the argument will write
  3. # the even numbered line to a file with name evenfile and odd numbered lines
  4. # in a text file called oddfile.
  5. # -------------------------------------------------------------------------
  6. # Copyright (c) 2001 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.  
  13. file=$1
  14. counter=0
  15.  
  16. eout="evenfile.$$" # even file name
  17. oout="oddfile.$$" # odd file name
  18.  
  19. if [ $# -eq 0 ]
  20. then
  21. echo "$(basename $0) file"
  22. exit 1
  23. fi
  24.  
  25. if [ ! -f $file ]
  26. then
  27. echo "$file not a file"
  28. exit 2
  29. fi
  30.  
  31. while read line
  32. do
  33. # find out odd or even line number
  34. isEvenNo=$( expr $counter % 2 )
  35.  
  36. if [ $isEvenNo -ne 0 ]
  37. then
  38. # even match
  39. echo $line >> $eout
  40. else
  41. # odd match
  42. echo $line >> $oout
  43. fi
  44. # increase counter by 1
  45. (( counter ++ ))
  46. done < $file
  47. echo "Even file - $eout"
  48. echo "Odd file - $oout"


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

Click here to subscribe via email.

  • Gagan


    ODDRE="^ [0-9]*[13579]"
    cat -n $1 | grep "$ODDRE" | cut -b 8- > oddfile.$$
    cat -n $1 | grep -v "$ODDRE" | cut -b 8- > evenfile.$$

Previous Script:

Next Script: