1

I have a big csv full that looks like so

else if(a,b,c,d,e)
else if(a,b,c,d,f)

I want to make it look like so

else if(a+x==b and b+x==c and c+x==d and d+x==e)
else if(a+x==b and b+x==c and c+x==d and d+x==f)

I don't always have 5 variables, some rows have less than that, 5 is maximum, 2 is minimum.

basically remove the commas and add after each variable, var+x==var2 and var2+x==var3; making it look like a C++ if statement. Is that doable in sed, awk or perl? I'm mostly interested in awk, for learning purposes, but any solution is good if it works.

2
  • did you want a space before ( ? Oct 23, 2014 at 11:26
  • @AvinashRaj not necessarily, i edited my question, i want to edit whats inside the ()
    – Lynob
    Oct 23, 2014 at 11:27

3 Answers 3

4

One way:

echo "else if(a,b,c,d,e)" | perl -pe 's/,([a-z])(?=[^)])/+x==$1 and $1/g; s/,([a-z])/+x==$1/'
2

Skip the perl part and try this:

awk -F',' '{x = $1"+x=="$2; \
    for (i=2; i< NF; i++) { \
         x = x " and " $i "+x=="$(i+1) \
    }; \
    print "else if" x \
}'

Effect:

$ echo '(a,b,c,d,e)' | awk -F',' '{x = $1"+x=="$2; \
quote>     for (i=2; i< NF; i++) { \
quote>          x = x " and " $i "+x=="$(i+1) \
quote>     }; \
quote>     print "else if" x \
quote> }'
else if(a+x==b and b+x==c and c+x==d and d+x==e)

It wouldn't be too difficult to make it work with the output of perl (with the else if already in), but using one tool for the job is better if it doesn't complicate things (as in this case).

2

Pure textual python solution. It needs at least 2 variables, no maximum.

#!/usr/bin/env python3

sourcefile = "/path/to/sourcefile"

def newline(oldline):
    subject = oldline.replace(" ", "").split("(")[-1].replace(")", "").split(",")
    out = [subject[i]+"+x=="+subject[i+1] for i in range(len(subject)-1)]
    print("else if("+" and ".join(out)+")")

with open(sourcefile) as sc:
    for line in [line.strip() for line in sc.readlines()]:
        newline(line)

Copy it into an empty file, save it as edit.py, set the path to the sourcefile, run it by:

python3 /path/to/edit.py

it converts:

else if(a,b)
else if(a,b,c,d,f)
else if(a,b,c,d,f,q,t)

into:

else if(a+x==b)
else if(a+x==b and b+x==c and c+x==d and d+x==f)
else if(a+x==b and b+x==c and c+x==d and d+x==f and f+x==q and q+x==t)

Not the answer you're looking for? Browse other questions tagged .