cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
645
Views
0
Helpful
1
Replies

Output foreach to a common file?

Cory Anderson
Level 1
Level 1

Hi,

I'm trying to output the results of a foreach statement to the same file for all instances.  Here's what I have going so far:

set $host"_CDP_FILE" |[open CDP_FILE.csv w]

set CDP [split [exec "show cdp neighbors | i Fas|Gi|Te"] \n]

#for each device in the cdp neighbor table

foreach line $CDP {

#get the neighbor hostname

  set CUR_DEV [lindex $line 0]

#get the local interface that connects to neighbor

  set LOC_INT [lindex $line 1][lindex $line 2]

#get the local neighbor platform

  set DEV_PLAT [lindex $line 5]

#get the remote interface

  set REM_INT [lindex $line 6][lindex $line 7]

#display output in a CSV format

  puts "$CUR_DEV,$LOC_INT,$DEV_PLAT,$REM_INT"

  }

it will display something like:
SW1,fa0/1,3750,fa1/0/1
SW2,fa0/2,3750,Gi1/0/1
SW3,fa0/3,3750,fa1/0/24
SW4,fa0/4,3750,fa1/0/1

I would like that output(ed?) to a .csv file.  If I put an output within the foreach loop it outputs the last iteration to the csv (of course), and nothing else.  Is there an easy work around to get the whole output?

Thanks,
Cory Anderson

1 Reply 1

Dan Frey
Cisco Employee
Cisco Employee

Puts output defaults to channelid STDOUT.   Try giving your puts statement the channelid of the filename. 

set host [open CDP_FILE.csv w]

set CDP  [split [exec "show cdp neighbors | i Fas|Gi|Te"] \n]

foreach line $CDP {

  set CUR_DEV [lindex $line 0]

  set LOC_INT [lindex $line 1][lindex $line 2]

  set DEV_PLAT [lindex $line 5]

  set REM_INT [lindex $line 6][lindex $line 7]

  puts $host "$CUR_DEV,$LOC_INT,$DEV_PLAT,$REM_INT"

}