Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a directory of .txt files. For each, i'd like to grab the 2nd and 7th line, and add those lines to another file, which I've arbitrarily named list.index. I'm not sure how to tell sed about the current filename, within the for loop, so what I have below doesn't work yet.

for i in *.txt
sed -n -e '2p' -e '7p' list.index
share|improve this question
I guess something like find -name \*.txt -exec sed -n -e '2p;7p' {} \; > list.index should work as well – Hagen von Eitzen Jan 12 '14 at 21:28

In your case, you had told sed that print 2nd and 7th line of file list.index, not add those lines to it.

Try this:

for i in *.txt
    sed -n -e '2p;7p' < "$i" >> list.index

It will print 2nd and 7th line of each file .txt then add them to list.index.

share|improve this answer
This worked like a charm. I see now that I can use $i to name the file within a loop. And I can do >> list.index to define the file to print to. Thank you. – Dylan Kinnett Jan 11 '14 at 17:20

Note that you can tell sed to stop reading after it's read the 7th line, there's no point keeping reading after that:

#! /bin/sh -
for i in *.txt; do
  sed -e 2b -e 7q -e d < "$i"
done > list.index

(or sed '7q;2!d' < "$i" shorter but slightly less legible)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.