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
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- 10 Greatest Open Source Software Of 2009
- My 10 UNIX Command Line Mistakes
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
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.
- Download Script
- Email this to a friend
- Rss Feed
- Last Updated: 09/17/08
{ 4 comments… read them below or add one }
# 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
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?
@lloyd
you can do that by
head -60 file1 >> output.txt | head -60 file2 >> output.txt
@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