You're viewing a comment by Abhishek and its responses.

Abhishek Permalink
July 24, 2014, 07:57

I have one question...
say i have a set of sed commands in file (All replace and delete statements)
i run those file commands on any file using -f . sed -f commandSetFile InputFile
Now i ran into a condition where i need to run those commands only on the even no lines of a given file i.e run the sed commandSetFile commands only on line no 2,4,6 and so on.
How can i do that ?

Comment Responses

Anirudh Permalink
March 05, 2015, 05:31

Your basic premise is flawed, i.e., of running a sedcommand file on a certain range of lines. That's not how sed is modeled to run. It will try to apply every command in the sed recipe to each line of the file, unless we intervene to change the flow (by means of, of course, the sed control flow commands).

So, coming to your particular case of wanting to run some commands on even numbered lines only we can take recourse of the "N" command. With this, we are instructing "sed" to operate on 2 lines at any time, then delete the first portion(odd numbered lines) & what remains is the even lines.
This would work fine in case the file had a even numbered of total lines. For the case of odd number of lines in a file, we delete the line if it contains just one line(the last line

/\n/!d;#<-deletes the last line for file with odd line total
# when we reach here we are sure to contain
# only even numbered lines.
# so put your sed commands underneath

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "apple_117": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.