1
votes

When reading from a csv file, the LaTeX package csvsimple updates the value of a variable, say \location, identifying a certain column.

I would like that the value of \location be displayed in the text, only when its value actually changes.

The following piece of code doesn't work.

    \documentclass{article}
    \usepackage{csvsimple}
    \usepackage{ifthen}
    \begin{document}

    \def\oldlocation{}

    \csvreader[head to column names,separator=tab]{input.tab}{}{%
       \ifthenelse{\equal{\oldlocation}{\location}}{\relax}{%
          \begin{center}\location{}\end{center}
          \element{}\\
          \renewcommand{\oldlocation}{\location}}
    }
    \end{document}

sample input.tab:

    location[tab]element
    Shelf 1 [tab] Item A
    Shelf 1 [tab] Item B
    Shelf 1 [tab] Item C
    Shelf 1 [tab] Item D
    Shelf 1 [tab] Item E
    Shelf 2 [tab] Item F
    Shelf 2 [tab] Item G
    Shelf 2 [tab] Item H
    Shelf 2 [tab] Item I
    Shelf 2 [tab] Item J
    Shelf 3 [tab] Item K
    Shelf 3 [tab] Item L
    Shelf 3 [tab] Item M
    Shelf 3 [tab] Item N
    Shelf 3 [tab] Item O

Expected output:

          Shelf 1
Item A
Item B
Item C
Item D
Item E
          Shelf 2
Item F
Item G
Item H
Item I
Item J
          Shelf 3
Item K
Item L
Item M
Item N
Item O
1
@Werner: Yes, thanks. Please, see edited question.ggna

1 Answers

1
votes

The problem with your current setup is the update of \oldlocation. Using

\renewcommand{\oldlocation}{\location}

does not expand \location to its current meaning. It merely sets \oldlocation to recall \location when executed. This is fixed when using

\edef\oldlocation{\location}

The code below provides what you're after with some minor re-arrangements of the conditional code:

enter image description here

\documentclass{article}

\usepackage{csvsimple}

\begin{document}

\def\oldlocation{}

\csvreader[head to column names,separator=tab]{input.tab}{}{%
  \expandafter\ifx\expandafter\oldlocation\location\else
    \begin{center}\location{}\end{center}%
    \edef\oldlocation{\location}
  \fi
  \element{}\\
}

\end{document}

You could have also used the following e-TeX conditional:

  \ifnum\pdfstrcmp{\oldlocation}{\location}=0\else

which compares the string expansion of \oldlocation with \location, and returning 0 of they are equal.


You may also consider using datatool for this kind of setup.