Shell Script To Delete All Even Numbered Line From a Text File

by on September 17, 2008 · 4 comments

Shell Script To Delete All Even Numbered Line From a Text File

  1. #!/bin/bash
  2. # Write a shell script which deletes all even numbered line from a text file.
  3. # -------------------------------------------------------------------------
  4. # Copyright (c) 2008 nixCraft project <http://cyberciti.biz/fb/>
  5. # This script is licensed under GNU GPL version 2.0 or above
  6. # -------------------------------------------------------------------------
  7. # This script is part of nixCraft shell script collection (NSSC)
  8. # Visit http://bash.cyberciti.biz/ for more information.
  9. # -------------------------------------------------------------------------
  10.  
  11. file=$1
  12. counter=0
  13.  
  14. out="oddfile.$$" # odd file name
  15.  
  16. if [ $# -eq 0 ]
  17. then
  18. echo "$(basename $0) file"
  19. exit 1
  20. fi
  21.  
  22. if [ ! -f $file ]
  23. then
  24. echo "$file not a file!"
  25. exit 2
  26. fi
  27.  
  28. while read line
  29. do
  30. # find out odd or even line number
  31. isEvenNo=$( expr $counter % 2 )
  32.  
  33. if [ $isEvenNo -eq 0 ]
  34. then
  35. # odd match; copy all odd lines $out file
  36. echo $line >> $out
  37. fi
  38. # increase counter by 1
  39. (( counter ++ ))
  40. done < $file
  41. # remove input file
  42. /bin/rm -f $file
  43.  
  44. # rename temp out file
  45. /bin/mv $out $file


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

Click here to subscribe via email.

  • Kiat Huang

    # This does the same thing quicker and with greater flexibility

    # e.g. delete every 2nd line starting from the 0th line
    sed ’0~2d’ -i $file

    # e.g. delete every 2nd line starting from the 1st line
    sed ’1~2d’ -i $file

  • lloyd

    I want to combine to text file in unix. Both text files have 100 lines each, i want to only take the 1st 60 line from the 1st file and combine it with the 2nd file.

    How do i do that?

  • cercatrova

    @lloyd

    you can do that by

    head -60 file1 >> output.txt | head -60 file2 >> output.txt

  • cercatrova

    @Kiat Huang

    for some reason your simplified command does not work on my mac. But the following works like a charm.

    for even lines
    sed -e ’1d;n;d’ yahoo.txt

    for odd lines
    sed -e ’2d;n;d’ yahoo.txt

Previous Script:

Next Script: