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

How to duplicate full word by partial match in sed

I have a file in which each line has the following format:

foo         tc_TESTNAME,  // TEST #1

I would like to duplicate tc_TESTNAME in each line as follows:

foo         tc_TESTNAME tc_TESTNAME,  // TEST #1

Following sed command only duplicates the matching part of the word:

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

# sed -e "s/(tc_*)/& &/"
foo         tc_ tc_TESTNAME,  // TEST #1

What is the correct regex syntax to duplicate the whole word?

>Solution :

With your shown samples please try following sed program.

sed -E 's/(tc_[^,]+)/\1 \1/' Input_file

OR: to match exact word starting from tc just in case you may have other strings then make sure space is present in regex like:

sed -E 's/ (tc_[^,]+)/ \1 \1/'  Input_file

Explanation: Using -E option to enable ERE(extended regular expression) and in main program using s option to perform substitution. Then matching (tc_[^,]+) which captures from tc_ just before next comma comes and capturing this value into 1 capturing group. While substituting it substitute it with itself space and itself as per required output.

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