0

I have two files,

file.1
 $ cat file.1 
this is the stuff that needs to be copied.
and file.2
$ cat file.2
aaaa
aaaa
aaaa
aaaa

bbbb
bbbb
bbbb
bbbb

cccc
cccc
cccc
cccc

dddd
dddd
dddd
dddd

I would like to copy the contents of file.1 to file.2 after the last match of bbbb.

So it would be something along the lines of:

cat file.1 >> file.2

but that only appends to the end of the file, so maybe

cat file.1 >> file.2 | grep bbbb

but that doesn't work like I would like.

The outcome should be:

$ cat file.2
aaaa
aaaa
aaaa
aaaa

bbbb
bbbb
bbbb
bbbb

this is the stuff that needs to be copied.

cccc
cccc
cccc
cccc

dddd
dddd
dddd
dddd
AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
Antzzz
  • 1
  • 1
  • title should display: "copy file content to target file. After last match of pattern in target file. Content from original file displays on next line of target file" – Antzzz May 23 '15 at 08:31
  • Show your desired output for that sample input. – Cyrus May 23 '15 at 10:25
  • Did you have already solved it. Or you are still waiting for an answer. – Roselover May 24 '15 at 06:42

1 Answers1

0

You have some undefined cases. What should happen in the event you have the following file?

aaaa
aaaa
bbbb
bbbb
cccc
cccc
bbbb
bbbb

Do you want to read it in only once after the very last bbbb or do you want to read it in once after each transition from bbbb to something non-bbbb (in this case, either "cccc" or the EOF)? If you only want the last bbbb, then you can create an editing shell-script for ed:

#!/bin/sh
ed "$1" <<EOF
1
?bbbb?r file.2
w
q
EOF

Then make it executable

chmod ugo+x my_script.sh

Then you can invoke it on the files you want:

find . -type f -name '*.txt' -exec ./my_script.sh {} \;

Note that the file-spec (*.txt) should not catch the sh/ed script, nor should it catch the template (file.2).

If you want to catch the bbbb-to-non-bbbb transition, even if it happens multiple times in the file, you'd need to clarify that.

Gumnos
  • 403
  • 3
  • 7