Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to copy lines 10 to 15 of a file into another file, in unix?

Tags:

linux

unix

I want to copy lines 10 to 15 of a file into another file in Unix.

I am having files file1.txt and file2.txt.

I want to copy lines 10 to 15 from file1.txt to file2.txt.

like image 782
sri Avatar asked Nov 15 '17 02:11

sri


People also ask

How do I copy a line from one file to another in Linux?

You can use grep to search for a regular expression in details. txt and redirect the result to the new file. If not you will have to search for each line you want to copy, still using grep, and append them to new. txt using >> in stead of > .

How do I copy data from one file to another in Unix?

You can use the shell commands cp or pax or the TSO/E command OCOPY to copy files within the z/OS UNIX file system. Using the shell: Use the cp shell command to copy: One file to another file in the working directory, or to a new file in another directory.

How do you copy a line in Unix?

To copy a line requires two commands: yy or Y ("yank") and either p ("put below") or P ("put above"). Note that Y does the same thing as yy . To yank one line, position the cursor anywhere on the line and type yy .


2 Answers

Open a terminal with a shell then

sed -n '10,15p' file1.txt > file2.txt 

Simple & easy.

If you want to append to the end instead of wiping file2.txt, use >> for redirection.

sed -n '10,15p' file1.txt >> file2.txt                           ^^ 

AWK is also a powerful command line text manipulator:

awk 'NR>=10 && NR<=15' file1.txt > file2.txt 
like image 61
iBug Avatar answered Sep 21 '22 10:09

iBug


In complement to the previous answer, you can use one of the following 3 solutions.

sed

Print only the lines in the range and redirect it to the output file

sed -n '10,15p' file1.txt > file2.txt 

head/tail combination

Use head and tail to cut the file and to get only the range you need before redirecting the output to a file

head -n 15 file1.txt | tail -n 6 > file2.txt 

awk

Print only the lines in the range and redirect it to the output file

awk 'NR>=10 && NR<=15' file1.txt > file2.txt 
like image 20
Allan Avatar answered Sep 20 '22 10:09

Allan