0

I'd like to repeat the row n times with a separator in-line (i.e. not generate extra rows). E.g. for the file example.csv with two rows

0.1\r\n
0.2\r\n

The result for n=3 and comma as a separator would be

0.1,0.1,0.1\r\n
0.2,0.2,0.2\r\n

I tried it with a paste command for n=2:

paste -d, example.csv example.csv

However, the EOLs are pasted too:

0.1\r,0.1\r\n
0.2\r,0.2\r\n
  • Are those literal \r\n? i.e. four literal characters? – Sparhawk Apr 15 at 8:27
  • @Sparhawk I meant "\r\n" as end-of-line, not literal characters – Max Li Apr 15 at 8:28
  • For me, your paste command works well. You might have an issue due to \r\n being Windows line endings. Run dos2unix example.csv example_unix.csv and then paste -d, example_unix.csv example_unix.csv – pLumo Apr 15 at 8:34
  • @RoVo ... and n times? – Max Li Apr 15 at 8:46
  • So in the final code block, are you using a combination of interpreted newlines and literal newlines? Hence my confusion. – Sparhawk Apr 15 at 8:47
3

After you fixed your line endings with

dos2unix example.csv

You can use printf to repeat the filename n times.

paste -d, $(printf 'example.csv %.0s' {1..10})

or if $n is a variable use seq instead of brace expansion:

paste -d, $(printf 'example.csv %.0s' $(seq 1 $n))

(via)

1

Assuming that there is no requirement to keep line ends as is and it can be converted to unix style do that as first step:

dos2unix file

For second step use awk:

awk '{for(i=1;i<=3;i++){if(i>1)printf ",";printf $0};printf "\n"}'

awk will in cycle construct the string putting there as many repetitions as you specify in i<=3 part.

if is required to ensure that you have , only between repetitions.

end result will be unix-style output. you might convert it back to dos if you need with unix2dos.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.