Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.


I would like to know is it possible to copy line number 7,8,9 and 17,18 of one text file to another one?

Thanks much in advance!!!

share|improve this question

3 Answers 3

up vote 1 down vote accepted

You can use sed (stream editor) to selectively print lines by number e.g.

sed -n '7,9p;17,18p' oldfile > newfile
share|improve this answer
    
Thank you much for your help!!!! –  yyyzzz Oct 6 '13 at 17:11

you should not rely on the order of the lines on a file, because it might change (if it is a system file, a temp file ecc. and it's updated).
You can use grep or one of its variants, for example rgrep:

rgrep WordOrRegularExpressionToMatch "Name_of_the_file"

Then, after you see that the lines printer are right, you can use:

rgrep WordOrRegularExpressionToMatch "Name_of_the_file" >> "Name_of_the_second_file"

It will append the lines printed by rgrep to the second file; to overwrite use ">" and not ">>".
If you really want to extract a precise set of lines you can use "sed":

sed -n -e 7,9p -e 17,18p "Name_of_the_file"

(these are 2 separate intervals)

So...

sed -n -e 7,9p -e 17,18p "Name_of_the_file" > "Another_file_to_overwrite"

(>> to append> Copy & paste the line: it will do the job. :-)
"man sed" will give you more help.
Have a nice day!

share|improve this answer

If you know how many lines are there in your source file (wc -l) you can do this .. assume 12000 lines and you want lines 2000 - 7000 in your new file (total of 5000 lines).

cat myfile | tail -10000 | head -5000 > newfile

Read the last 10k lines, then read the 1st 5k lines from that.

share|improve this answer
    
Thank you much for your help!!! It is very interesting approach, thank you. –  yyyzzz Oct 6 '13 at 17:13
1  
You could at least post the link to the original answer : stackoverflow.com/questions/9259658/… .. or do the decent thing and answer it without the use of copy/paste .. –  FreudianSlip Oct 6 '13 at 17:42

Your Answer

 
discard

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.