Shell Script To Write Odd and Even Line To Respective Files

by Vivek Gite [Last updated: September 17, 2008]

in Academic, Decision Making, File-management

#!/bin/bash
# Write a shell script that, given a file name as the argument will write
# the even numbered line to a file with name evenfile and odd numbered lines
# in a text file called oddfile.
# -------------------------------------------------------------------------
# Copyright (c) 2001 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
 
eout="evenfile.$$" # even file name
oout="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 -ne 0 ]
	then
		# even match
		echo $line >> $eout
	else
		# odd match
		echo $line >> $oout
	fi
	# increase counter by 1
	(( counter ++ ))
done < $file
echo "Even file - $eout"
echo "Odd file - $oout"
Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our email newsletter to make sure you don't miss a single tip/tricks.

{ 1 comment… read it below or add one }

Gagan 10.16.08 at 1:00 am


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

Leave a Comment

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

Tagged as: , , , , , , , , , , ,

Previous post: Shell Script To Combine Any Three Text Files Into a Single File

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