Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file that consists of a single line:


I want to convert this into


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 '14 at 12:21
A pythonly solution will help but is not a necessary requirement – Stormvirux Feb 26 '14 at 12:24
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
Why is this a Unix & Linux question and not a StackOverflow question? – kojiro Feb 26 '14 at 14:48
@kojiro why this quesiton not on hold as unclear ? – Kiwy Feb 26 '14 at 14:50
up vote 3 down vote accepted


#!/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 :-) – user55518 Feb 27 '14 at 1:49

Using sed:

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

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; '

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}'
share|improve this answer

A Perl way:

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

Your Answer


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.