3

I have an array in a CSV file as

input.csv
"{1,2,3,4}"
"{1,2,3,4,5,6,7,8,9}"
"{34,6,7,89}"

I want to get the first and the last element of this CSV file as another CSV file

output.csv
    1,4
    1,9
    34,89

I tried with

  cut -d , -f1 -- complement input.csv > output.csv

I know this works for normal CSV.But here I have curly braces and "" too.

3

I would do it this way with sed

$ sed -r 's/"\{([0-9]+,).*,([0-9]+)\}"/\1\2/' input
1,4
1,9
34,89

Notes

  • -r use ERE
  • \} literal {
  • ([0-9]+,) save some digits followed by a comma for later
  • \1\2 back reference to saved patterns

(your output is indented, - so maybe you want / \1\2/ or /\t\1\2/ in the replacement - adjust as you like)

2

One way:

awk -F"[}{,]" '{print $2, $(NF-1)}' OFS=,  file

You can use the curly braces also as delimiters and hence the elements can be accessed directly.

2

Using sed:

sed -e 's/,.*,/,/' -e 's/[^0-9,]//g' file

The first s command replaces everything between the first and last comma with a comma, effectively eliminating all content in between.

The second s command removes all characters that are not a digit or a comma.

1

this code will work for you

cat input.csv|sed 's/\"//g'|sed 's/{//g'|sed 's/}//g'|awk -F "," '{print $1,",",$NF}'|tr -d " " > output.csv

sed 's/\"//g' will eliminate the ", sed 's/{//g'|sed 's/}//g' will eliminate the braces, awk -F "," '{print $1,",",$NF}' will give you this result

1 , 4
1 , 9
34 , 89

and tr -d " " will eliminate the spaces in the output

  • 2
    you know sed 1) can use multiple susbstitute 2) can have a file of its own ? – Archemar Dec 26 '16 at 9:28
  • yes by using the -e option or the ; but i want to make it simple – Dababi Dec 26 '16 at 9:42
-1
sed -r "s/(\"|\{|\})//g" input.csv|awk -F, '{print $1","$NF}'

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.