Ashwin Geet D'Sa
Ashwin Geet D'Sa

Reputation: 7379

Command line or bash method to copy the contents of file to itself

I have a file named fileName.txt and the sample contents can be assumed as below:

first few lines to be ignored

abc
def
ghi
klm

I want a resultant file to look like this

first few lines to be ignored

abc
def
ghi
klm


abc
def
ghi
klm

abc
def
ghi
klm

I want to know a command-line method or bash method to replicate the lines (assuming that I know the line numbers) within the same file.

Is there a simple way to do it?

Upvotes: 0

Views: 253

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84579

Assuming you can specify the lines to duplicate, then you can pick the lines from your file with sed -n 'x,yp' file, loop as many times as you care to duplicate them, then using redirection, write the duplicated lines to a temp-file. Then it is simply a matter of appending the temp-file to your original file. To duplicate lines 2-6 (twice), you could do something like:

(for i in {1..2}; do sed -n '2,6p' file; done) > mytmp && cat mytmp >> file

(note: the (...) > mytmp simply executes the loop in a subshell and then redirects all output from the subshell to mytmp)

Given your input file of:

$ cat file
first few lines to be ignored

abc
def
ghi
klm

The result duplicating lines 2-6 would be:

$ cat file
first few lines to be ignored

abc
def
ghi
klm

abc
def
ghi
klm

abc
def
ghi
klm

Let me know if that is what you had in mind.

Upvotes: 1

Related Questions