About

Script Categories

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

Posted in Academic » Decision Making » File-management

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

#!/bin/bash
# Write a shell script which deletes all even numbered line from a text file.
# -------------------------------------------------------------------------
# Copyright (c) 2008 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
counter=0
 
out="oddfile.$$" # odd file name
 
if [ $# -eq 0 ]
then
	echo "$(basename $0) file"
	exit 1
fi
 
if [ ! -f $file ]
then
	echo "$file not a file!"
	exit 2
fi
 
while read line
do
	# find out odd or even line number
	isEvenNo=$( expr $counter % 2 )
 
	if [ $isEvenNo -eq 0 ]
	then
		# odd match; copy all odd lines $out file
		echo $line >> $out
	fi
	# increase counter by 1
	(( counter ++ ))
done < $file
# remove input file
/bin/rm -f $file
 
# rename temp out file
/bin/mv $out $file

Download - Email this to a friend - Printable version

Is your site working? Monitor Your Web Site 24/7. Get SMS alerts on server downtime! Free 30-day trial including 20 SMS!

Related Other Helpful Shell Scripts:

Discussion on This Shell Script:

  1. Kiat Huang Says:

    # 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

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags: , , , , , , , , , , , , , ~ Last updated on: September 17, 2008