Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate strings in each line using bash?

Tags:

string

bash

I have a text file containing strings in each line like this:

'abc',
'dog',
'zebra',

I want to make it like:

'abc', 'abc',
'dog', 'dog',
'zebra', 'zebra',

How best to do it in bash?

like image 413
Jand Avatar asked Sep 14 '25 15:09

Jand


1 Answers

You could call sed:

sed -r 's/(.*)/\1 \1/' dupcol.csv

The .* says to match any character on a line, repeatedly. The ( ) around it says to store the match in the first register (\1). Then the full match is output twice.

I just usually default to using sed’s -r option to make for cleaner (extended) regexes. However, omitting the -r enables & to match the full pattern. So a simpler version of this special case where you want to keep the full match is:

sed -r 's/.*/& &/' dupcol.csv

If you want to change the file in-place, add the -i option.

like image 71
Micah Elliott Avatar answered Sep 17 '25 05:09

Micah Elliott