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?

2
  • 1
    This could work too...paste -d " " dupcol.csv dupcol.csv Commented Aug 14, 2015 at 4:22
  • Possible duplicate of How to duplicate string in Bash? Commented Jul 1, 2019 at 12:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Worked like a charm. Thanks. Would be more informative if you also explain what \1 \1 does.
As you are using everything matched you can just use & without any capture groups or need for -r. sed 's/.*/& &/'
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.