Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

for loop using cat command

Status
Not open for further replies.

yukonxl

Programmer
Jan 4, 2002
4
US
I am writing a shell script and must use the korn shell. I have a comma delimited file with some spaces in the data and I need to use a for loop to read each record for additional processing.

File layout of file.csv (sample):
"Record 1","Field 2","Field 3","Field 4"
"Record 2","Field 2","Field 3","Field 4"

I am trying to use the following code (simplified for demonstration purposes) to read each line in the file:

nCounter=1
for newRecord in `cat file.csv`
do
echo "$nCounter $newRecord"
nCounter=`expr $nCounter + 1`
done

My problem is this...the for ... in `cat ...` doesn't work when there are spaces in the records. So I am getting the following:
1 "Record
2 1","Field
3 2","Field
4 3","Field
4 4"
5 "Record
6 2","Field
...

I want it to read the whole line (until end of line) not a portion of each line (until space). I need the following results:
1 "Record 1","Field 2","Field 3","Field 4"
2 "Record 2","Field 2","Field 3","Field 4"

Any help would be GREATLY appreciated.

Thanks,

Rick
 
Hello
This is an easy one...
But not in the shell per-se..
awk ' {
for (x=1 ; x <= NR ; x++) {
if (NR == x) {
print x, $0
}
}
}' filename

output:
1 file1,file2,file3,file4
2 file3,file4,file6,file7
3 file5,file6,file7,file8
4 file17,file,5,file78,file12

The only problem you may have is with the quotes..

I did this:
awk ' {
as above
}' | sed 's/^/&quot;/g;s/$/&quot;/g' But That is because I have forgotten how to select char depths in sed lines:(

 
nCounter=1
while read newRecord
do
echo &quot;$nCounter $newRecord&quot;
nCounter=`expr $nCounter + 1`
done < file.csv Jean Pierre.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top