Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy regex pattern to another location using awk

Assume I have a file input.txt with the following contents:

Hello my name is: 1234.
My favorite color is blue.
This was my code from the introduction line: replace-with-code

Hello my name is: 1122.
My favorite color is blue.
This was my code from the introduction line: replace-with-code

I want to create an output.txt which looks like this:

Hello my name is: 1234.
My favorite color is blue.
This was my code from the introduction line: 1234

Hello my name is: 1122.
My favorite color is blue.
This was my code from the introduction line: 1122

The proposed way from here: Copy contents from capture group to another subsequent line :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

awk '/[0-9]{4}./ {match($0,"([0-9]{4})",n);}{gsub(/replace-with-code/,n[0]); print}' inputfile > outputfile

Returns an error. I am just not able to fix this issue… Any awk magicians can help me here?

>Solution :

Here is an awk solution:

awk '{gsub(/replace-with-code/, p)} /[0-9]{4}\.$/ {p = $NF+0} 1' file

Hello my name is: 1234.
My favorite color is blue.
This was my code from the introduction line: 1234

Hello my name is: 1122.
My favorite color is blue.
This was my code from the introduction line: 1122
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading