Satish
Satish

Reputation: 17407

sed/awk copy paste snippet from one place to other place in same file

How do i copy some snippet and paste in same file using sed/awk tool?

Example: file name foo.txt has following text i want to copy that and paste below that same text

ABC
DEF
GHI
JKL
MNO
PQR

Final output will be like.

    ABC
    DEF
    GHI
    JKL
    MNO
    PQR

    ABC
    DEF
    GHI
    JKL
    MNO
    PQR

Upvotes: 1

Views: 1015

Answers (3)

John B
John B

Reputation: 3646

As Fedorqui points out in his comment, you can run Awk on the same file multiple times.

awk 'NR>1 && FNR==1 {print ""} {print "\t" $0}' foo.txt foo.txt

should produce your desired output.

This can be simplified using bash brace expansion foo.txt{,}.

Also, if using GNU Awk, there's builtin rule called ENDFILE that will allow you act after the last record has been processed in each file:

awk '{print "\t" $0} ENDFILE{print ""}' foo.txt{,}

Alternatively, you could be a hog and read the entire file into memory, then loop through it twice.

awk '{
    a[NR]=$0
} END {
    num=2
    for (i=1; i<=num; i++) {
        for (j=1; j<=NR; j++)
            print "\t"a[j]
        if (i % num != 0)
            print ""
    }
}' foo.txt

You'll notice each line number NR must also be recorded as an index of the array a to preserve the original order in output.

Upvotes: 1

bufh
bufh

Reputation: 3410

OP asked for sed, so here it is!

There are probably many way to achieve it, but here is the one I know:

sed 'H;$G' foo.txt
  • H: append current file to the hold buffer
  • ;: separate two expressions
  • $: upon end of file
  • G: print hold buffer

But wait! there is more!

Don't ever forget that ed Is The Standard Text Editor (took me some time to remember how to use it and it was not brillant I must say).

For the example let's say it's in a file named foo.ed (you could do the same in an interactive session):

$a

.
,t$
$d
wq

Then use it with:

ed foo.txt < foo.ed

One-liner unreadable bashism:

ed foo.txt <<< $'$a\n\n.\n,t$\n$d\nwq'

Translation:

  • $a: insert at the end of the file everything (a single new line here) till the single dot .
  • ,t$: copy the whole file content to the end
  • $d: delete the last line because I didn't remember how to copy till the line before the end of the file !@#
  • wq: write and quit

References:

Upvotes: 6

Ed Morton
Ed Morton

Reputation: 203229

Assuming you want to duplicate a whole file and don't really want to indent the output lines, you'd never use sed or awk for this, just cat and echo:

$ cat file; echo ''; cat file
$ cat file
ABC
DEF
GHI
JKL
MNO
PQR

ABC
DEF
GHI
JKL
MNO
PQR

and if you want to modify the original file, just redirect the output to a tmp file and then mv it to file:

(cat file; echo ''; cat file) > tmp && mv tmp file

Upvotes: 4

Related Questions