Print 2nd and 7th lines to a file using `sed`

Dyl*_*ett 1 sed text-processing

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.

#!/bin/sh
for i in *.txt
do
sed -n -e '2p' -e '7p' list.index
done
Run Code Online (Sandbox Code Playgroud)

cuo*_*glm 5

在您的情况下,您已经告诉sed打印文件的第 2 行和第 7 行list.index,而不是将这些行添加到其中。

尝试这个:

#!/bin/sh
for i in *.txt
do
    sed -n -e '2p;7p' < "$i" >> list.index
done
Run Code Online (Sandbox Code Playgroud)

它将打印每个文件的第 2 行和第 7 行,.txt然后将它们添加到list.index.