Linux – cut the first and last element in CSV

awkcsvlinuxsedtext processing

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.

Best Answer

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)

Related Question