0

i want to parse a csv file in a shell script. I want to input the name of the file at the prompt. like :

somescript.sh filename

Can it be done?

Also, I will read user input to display a particular a particular data number in the csv. For example, say the csv file has 10 values in each line:

1,2,3,4,5,6,7,8,9,10

And I want to read the 5th value. how can I do it? And multiple lines are involved.

Thanks.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
amit
  • 10,133
  • 22
  • 72
  • 121
  • possible duplicate of [Bash shell scripting - CSV parsing](http://stackoverflow.com/questions/1560393/bash-shell-scripting-csv-parsing) [Shell script to parse thorough a file (csv) and process line by line](http://stackoverflow.com/questions/4439536/shell-script-to-parse-through-a-file-csv-and-process-line-by-line) – Jacob May 20 '11 at 06:32
  • Try using my FOSS CSV tool at http://code.google.com/p/csvfix –  May 20 '11 at 06:43

2 Answers2

2

If your file is really in such a simple format (just commas, no spaces), then cut -d, -f5 would do the trick.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1
#!/bin/sh

awk -F, "NR==$2{print \$$3}" "$1"

Usage:

./test.sh FILENAME LINE_NUMBER FIELD_NUMBER
Timofey Stolbov
  • 4,501
  • 3
  • 40
  • 45
  • how to account for the line no.? – amit May 20 '11 at 07:30
  • can you tell me what -F and NR mean? – amit May 20 '11 at 07:49
  • this is not working for me. i am typing this at the shell. it does nothing – amit May 20 '11 at 10:59
  • @amit: Of course. It's intended to work as `somescript.sh`. To use directly from command line type `awk -F, 'NR==6{print $5}' FILENAME_TO_PARSE`. – Timofey Stolbov May 20 '11 at 11:08
  • if i use it at the commandline, it works fine. but if i type the above code in a shell script and run it. it displays nothing. am i doing something wrong? – amit May 20 '11 at 11:27
  • im typing ./fetchvalue.sh newfile.csv 2 2 – amit May 20 '11 at 11:29
  • im typing exactly that. ./fetchvalue.sh newfile.csv 2 2 – amit May 20 '11 at 11:55
  • awk -F, 'NR==$2{print \$$3}' $1 + awk -F, NR==$2{print \$$3} newfile.csv syntax error The source line is 1. The error context is NR==$2{print >>> \ <<< $$3} awk: The statement cannot be correctly parsed. The source line is 1. – amit May 20 '11 at 11:57
  • i am using it exactly like you specified. still the error. the command is working fine. but when i put it inside a script, i cannot get teh results. please help? – amit May 23 '11 at 04:55