views:

1855

answers:

3

Attempting to print out a list of values from 2 different variables that are aligned correctly.

foreach finalList ($correctList $wrongList)
printf "%20s%s\n" $finalList
end

This prints them out an they are aligned, but it's one after another. How would I have it go through each item in each list and THEN go to a new line?

I want them to eventually appear like this:

Correct    Incorrect
Good1      Bad1
Good2      Bad2
Good3      Bad3

Good comes from correctList Bad comes from wrongList

Getting rid of \n makes it Like this:

Good1     Bad1    Good2    Bad2

I just want 2 columns.

A: 

try getting rid of the \n

Ray Tayek
then they just print all across. It ends up being Good1 Bad1 Good2 Bad2
Doug
@Ray: This misses the point of the question.
Jonathan Leffler
+4  A: 

You can iterate over both lists at the same time like this:

# Get the max index of the smallest list
set maxIndex = $#correctList
if ( $#wrongList < $#correctList ) then
  set maxIndex = $#wrongList
endif

set index = 1
while ($index <= $maxIndex)
  printf "%-20s %s\n" "$correctList[$index]" "$wrongList[$index]"
  @ index++
end
Robert Gamble
Suggestion - applicable to all languages using printf-like notations - would be to use "%-20s %s\n" (or "%-19s %s\n" if the second column should ordinarily start in column 21). This ensures that there is a space between the two values even if the first is longer than 20 (or 19) characters.
Jonathan Leffler
@Jonathan, I took your suggestion for this example but this is not always the desired behavior. For example, I often have to write routines to export data to fixed-width file formats where spaces aren't required between fields (and inserting extraneous spaces would break the layout).
Robert Gamble
A: 

I believe the pr(1) command with the -m option will help do what you want. Look at its man page to eliminate the header/trailer options and set the column widths.

Also, I recommend you not use the C-Shell for scripting; you'll find the sh-syntax shells (sh, bash, ksh, etc) are more consistent and much easier to debug.

mpez0