1

I would like to split a line such as:

name1=value1,name2=value2, .....,namen=valuen

two produce two lines as follows:

name1,name2, .....,namen
value1,value2, .....,valuen

the goal being to construct an sql insert along the lines of:

input="name1=value1,name2=value2, .....,namen=valuen"
namescsv=$( echo $input | sed 's/=[^,]*//g' )
valuescsv=$( echo $input | ?????? )

INSERT INTO table_name ( $namescsv ) VALUES ( $valuescsv )

Id like to do this as simply as possible - perl awk, or multiple piping to tr cut etc seems too complicated. Given the names part seems simple enough I figure there must be something similar for values but cant work it out.

3 Answers 3

3

You can just inverse your character match :

echo $input | sed 's/[^,]*=//g'
Sign up to request clarification or add additional context in comments.

1 Comment

fantastic. I was trying $input | sed 's/,[^=]*//g' , new it had to be someting close. knew I should have signed up to this site years ago
0

i think your best bet is still sed -re s/[^=,]*=([^,]*)/\1/g though I guess the input would have match your table exactly.

2 Comments

could you clarify why this would be better? my regex eyes are mediocre
ah no, the one above is just as good, although maybe a tad less rigorous.
0

Note that in some RDBMS you can use the following syntax:

INSERT INTO table_name SET name=value, name2=value2, ...;

http://dev.mysql.com/doc/refman/5.5/en/insert.html

The following shell script does what you are asking for and takes care of escaping (not only because of injection, but you may want to insert values with quotes in them):

_IFS="$IFS"; IFS=","
line="name1=value1,name2=value2,namen=valuen";

for pair in $line; do
        names="$names,${pair%=*}"
        values="$values,'$(escape_sql "${pair#*=}")'"
done
IFS="$_IFS"

echo "INSERT INTO table_name ( ${names#,} ) VALUES ( ${values#,} )"

Output:

INSERT INTO table_name ( name1,name2,namen ) VALUES ( 'value1','value2','valuen' )

1 Comment

thanks, good to know. however doesn't seem to be the case with sqlite3 that I am using for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.