4

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?

Jand
  • 2,527
  • 12
  • 36
  • 66

1 Answers1

6

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.

Micah Elliott
  • 9,600
  • 5
  • 51
  • 54
  • Worked like a charm. Thanks. Would be more informative if you also explain what `\1 \1` does. – Jand Aug 14 '15 at 02:15
  • As you are using everything matched you can just use `&` without any capture groups or need for `-r`. `sed 's/.*/& &/'` – 123 Aug 14 '15 at 07:28
  • Awesome tip on &. I had originally tried that but now see that it does not work with -r. I've added this into the answer. Thanks! – Micah Elliott Aug 14 '15 at 16:14