Shell Script To Write Odd and Even Line To Respective Files

#!/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"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
Category List of Unix and Linux commands
File Management cat
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN Alpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • Roel Pompen Aug 20, 2015 @ 12:16

    awk ‘NR % 2 {print > “odd”} ! (NR % 2) {print > “even”}’ inputfile
    This will split input file into files “even” and “odd”
    Or is this more about bash than invoking utilities? And what utilities are allowed then?
    /usr/bin/[ is not a builtin…

  • Gagan Oct 16, 2008 @ 1:00


    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 Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.