user3065582
user3065582

Reputation: 13

copy specific line of ith file to another file as ith line

I am going to do sdv calculation.

I have lots of files. Each file has 2000 lines. I only need the last line (2000th) of each file, and I want to copy each of them into one file.

For example,

last line of first file will be the first line of new file
last line of second file will be the second line of new file.
.......
......
last line of nth file will be nth line of the new file.

I am thinking something like this:

case=$1 # total numer of files
for (( i = 1; i <= $case ; i ++ ))
do
    file=PPD$i           # files are numbered as PPD1, PPD2.....PPDi
    some command.....>final.dat
done

Upvotes: 1

Views: 1842

Answers (2)

gentoomaniac
gentoomaniac

Reputation: 111

If you're always looking for the last line, use the following:

some command | tail -n 1 > final.dat

if you have already files all files and they contain a line break at the end, you could make it even more easy by doing this

tail -n 2 -q /path/to/files/* > final.dat

-n 2 in this case to get the linebreak in your output

Upvotes: 1

devnull
devnull

Reputation: 123528

Instead of

some command.....>final.dat

you can say:

sed '2000!d' $file >> final.dat

Be warned that the sed command would not produce any output if a file doesn't have 2000 lines.

Upvotes: 3

Related Questions