1

I'm trying to use sed/awk to copy a range of text from the beginning of file1 to a specific line. Then add that output to the beginning of file 2 for a script I'm writing.

The following command does what I want to extract from line 1 to the line that I want to end at in file1.

awk '1;/### BEGIN ###/{exit}' file1

However, I don't know how to get this content to be copied to the beginning of file2 which already has text in it. I experimented with sed below to add a new line to beginning of file2 which works.

sed -e '1i\A new line is added to top of document' > file2

How do I use the output of awk to sed to update file2? Is there a better way?

edit: I've been experimenting and this command works below. However, I'm still up to learn if there is other ways to do this that might be better or more efficent.

cat <(awk '1;/### BEGIN ###/{exit}' file1) file2 > file3

Sample text file1:

Line1
Line...
### BEGIN ###
additional text not wanted...

Sample text file2:

<insert text from file 1 above existing text>
Existing text...
2
  • Provide sample text from the files and the expected output. Commented May 8, 2021 at 18:43
  • You can copy something to the beginning of a file with the cat command: awk ... | cat - file1 > file2. The dash stands for standard input. The result is in file2; if needed, you can rename it file1. Commented May 8, 2021 at 19:02

1 Answer 1

0
$ python -c "for i in range(6): print('file1, line',i+1)" >file1

$ python -c "for i in range(6): print('file2, line',i+1)" >file2

$ head -n 3 file1  # "simulated" portion of file1 to prepend to file2
file1, line 1
file1, line 2
file1, line 3
   
$ (tac file2 && (head -n 3 file1 | tac) ) | tac >file3

$ cat file3
file1, line 1
file1, line 2
file1, line 3
file2, line 1
file2, line 2
file2, line 3
file2, line 4
file2, line 5
file2, line 6

$ mv file3 file2

Requirement: the extra mem-space while tac runs, and disk for file3, while it exists.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .