Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate full word by partial match in sed

Tags:

regex

sh

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:

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

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

like image 376
yildizabdullah Avatar asked Oct 17 '25 02:10

yildizabdullah


1 Answers

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

You attempted this sed:

sed -e "s/(tc_*)/& &/"

Which will only duplicate tc followed by 0 or more underscores. However what you want to match is tc_ followed by anything till next comma or whitespace.

With that in mind, following sed should work for you:

s='foo         tc_TESTNAME,  // TEST #1'
sed 's/tc_[^[:blank:],]*/& &/g' <<< "$s"

foo         tc_TESTNAME tc_TESTNAME,  // TEST #1

[^[:blank:],]* matches 0 or more of any character that is not a whitespace and not a comma.

Note that there is no need to use extended regex mode for this sed command.

like image 116
anubhava Avatar answered Oct 20 '25 05:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!