1

I have a file that consists of a single line:

a,x,b,c,d,e 

I want to convert this into

a,x,b,x,c,x,d,x,e,x

Which is the easiest way to achieve this? A solution based on Python will be most helpful

Also supposing that this file is a csv file will python make the work easier?

7
  • I see the tag python ? is it relevant or do you need az pythononly solution, because you better mention it expicitly. – Kiwy Feb 26 '14 at 12:21
  • A pythonly solution will help but is not a necessary requirement – Stormvirux Feb 26 '14 at 12:24
  • 1
    Given the various interpretations in the received answers, you should specify whether you want to insert literal “x” or the value of the 2nd field. – manatwork Feb 26 '14 at 13:40
  • 1
    Why is this a Unix & Linux question and not a StackOverflow question? – kojiro Feb 26 '14 at 14:48
  • 1
    @kojiro why this quesiton not on hold as unclear ? – Kiwy Feb 26 '14 at 14:50
3

Python

#!/usr/bin/env python

from sys import stdin

for line in stdin:
    parts = line.split(',')
    glue = parts.pop(1)
    print(',{0},'.format(glue).join(parts) + ',' + glue)
1
  • great reuse of input :-) – user55518 Feb 27 '14 at 1:49
3

Using sed:

echo 'a,x,b,c,d,e' | sed 's/,\([^x]\)/,\1,x/g'
3
sed 's/,x,/,/g;s/[^,]*/&,x/g'
2

I assume that your data is not actually what you show and instead, you want to repeat the 2nd column of a csv file, whatever that column may be, not only if it is an x. If so, these should work:

$ echo "a,x,b,c,d,e" | 
    perl -lpe 's/^(.+?),([^,]+)/$1/; $n=$2; s/([^,]+)/$1,$n/g; '
a,x,b,x,c,x,d,x,e,x

And in awk:

$ echo "a,x,b,c,d,e" | 
    awk -F, '{k=$1","$2","$3; for(i=4;i<=NF; i++){k=k","$2","$(i)} 
              print k","$2}'
a,x,b,x,c,x,d,x,e,x
1

A Perl way:

echo "a,x,b,c,d,e" |
 perl -lpe '@_= map { $_ => "x" } grep !/x/, split /,/,;$_=join ",",@_;'
a,x,b,x,c,x,d,x,e,x

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.