Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
I see the tag python ? is it relevant or do you need az pythononly solution, because you better mention it expicitly. –  Kiwy Feb 26 at 12:21
    
A pythonly solution will help but is not a necessary requirement –  Stormvirux Feb 26 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 at 13:40
1  
Why is this a Unix & Linux question and not a StackOverflow question? –  kojiro Feb 26 at 14:48
1  
@kojiro why this quesiton not on hold as unclear ? –  Kiwy Feb 26 at 14:50
show 2 more comments

5 Answers 5

up vote 3 down vote accepted

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)
share|improve this answer
    
great reuse of input :-) –  bersch Feb 27 at 1:49
add comment

Using sed:

echo 'a,x,b,c,d,e' | sed 's/,\([^x]\)/,\1,x/g'
share|improve this answer
add comment
sed 's/,x,/,/g;s/[^,]*/&,x/g'
share|improve this answer
add comment

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
share|improve this answer
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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