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

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

# Write a shell script which deletes all even numbered line from a text file.
# -------------------------------------------------------------------------
# Copyright (c) 2008 nixCraft project <>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit for more information.
# -------------------------------------------------------------------------
out="oddfile.$$" # odd file name
if [ $# -eq 0 ] 
	echo "$(basename $0) file"
	exit 1 
if [ ! -f $file ]
	echo "$file not a file!"
	exit 2
while read line
	# find out odd or even line number 
	isEvenNo=$( expr $counter % 2 )
	if [ $isEvenNo -eq 0 ] 
		# odd match; copy all odd lines $out file
		echo $line >> $out
	# increase counter by 1
	(( counter ++ ))
done < $file
# remove input file
/bin/rm -f $file
# rename temp out file 
/bin/mv $out $file
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics via:
Category List of Unix and Linux commands
Disk space analyzers ncdu pydf
File Management cat
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities NetHogs 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
4 comments… add one
  • cercatrova Jan 14, 2010 @ 0:05

    @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

  • cercatrova Jan 13, 2010 @ 23:44


    you can do that by

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

  • lloyd Apr 1, 2009 @ 17:41

    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?

  • Kiat Huang Sep 17, 2008 @ 22:40

    # 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

Your email address will not be published.

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