-2

I want to cut an array column in a CSV file. For example if you see the below CSV file

input.csv

1,2,"{1,2,3}",1

3,4,"{3,9,1}",2

8,9,"{10,12,30}",3

I want the output as

output.csv

1,2,3

3,9,1

10,12,30

I tried using cut -d , -f 3 input.csv and cut -d { -f 3 input.csv but both did not work .Any help is appreciated.Thanks in advance.

5
  • do you always want the last column and does the last column always have values enclosed in "{}"? Commented Oct 20, 2016 at 8:38
  • if above is true, try sed 's/.*{\|}"//g' input.csv Commented Oct 20, 2016 at 8:40
  • No It is not the last column.It is a column at the third position Commented Oct 20, 2016 at 8:42
  • 1
    cut -d\" -f2 input.csv | tr -d [{}] Commented Oct 20, 2016 at 8:43
  • cut -d , -f-2,5- input.csv | tr -d [}\"] Commented Oct 20, 2016 at 8:45

2 Answers 2

3

With awk you can define multiple field delimiters with -F'[]', so you can define both braces as delimiters and print the then second field:

awk -F'[{}]' '{print $2}' input.csv
1,2,3
3,9,1
10,12,30
0
$ cat input.csv
1,2,"{1,2,3}",1
3,4,"{3,9,1}",2
8,9,"{10,12,30}",3

$ sed -E 's/^([^,],){2}"\{([^}]+).*/\2/' input.csv
1,2,3
3,9,1
10,12,30
  • some sed versions used -r instead of -E for extended regex
  • ^([^,],){2} first two columns
  • "\{ match "{ in third column, not captured
  • ([^}]+) capture non} characters
  • .* rest of line
  • replace entire line with required string


With grep and pcre

$ grep -oP '^([^,],){2}"\{\K[^}]+' input.csv 
1,2,3
3,9,1
10,12,30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.