How to copy specific text in shell script?

Example:

1.) Inside the text file (FileA)

Header1 You  can do everything as long as you are determined to work hard in your life  End1 Header2 Honesty is the best policy End2 

Now, I want to copy the text from Header1 to End1. The output must only be:

Header1 You can do everything as long as you are determined to work hard in your life  End1 
Add Comment
2 Answer(s)

awk is rather useful parsing text files, try:

awk '/Header1/,/End1/ { print }' FileA

The will print the part of the file starting with Header1 and ending with the first occurrence of End1

To save the output to a file (FileB in this case):

awk '/Header1/,/End1/ { print }' FileA > FileB

Answered on August 1, 2020.
Add Comment

Quick Regex to match the WHOLE first segment: https://regex101.com/r/r9e7bB/1

$re = '/Header1.*End1/ms'; 

And if you want to match the inbetween only: https://regex101.com/r/r9e7bB/2

$re = '/Header1(.*)End1/ms'; 

or in shell, simply:

grep -zo "Header1.*End1" FileA 
Answered on August 1, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.