Jand
Jand

Reputation: 2727

How to duplicate strings in each line using 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?

Upvotes: 4

Views: 1683

Answers (1)

Micah Elliott
Micah Elliott

Reputation: 10264

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.

Upvotes: 6

Related Questions