English 中文(简体)
tail() function in XQuery
原标题:

Is there a way in XQuery to do something like a tail() function?

What I m trying to accomplish is to get the contents of a file (using "xdmp:filesystem-file($path)") and then display only the last 100 lines. I can t seem to find a good way to do this. Any ideas?

Thank you.

问题回答

In plain XQuery, this can be accomplished by splitting into lines and getting the desired number of lines from the end of the sequence, then rejoining them, if necessary, i.e.

declare function local:tail($content as xs:string, $number as xs:integer)
{
  let $linefeed := "
"
  let $lines := tokenize($content, $linefeed)
  let $tail := $lines[position() > last() - $number]
  return string-join($tail, $linefeed)
};

A pure and short XPath 2.0 solution -- can be used not only in XQuery but in XSLT or in any other PL hosting XPath 2.0:

for $numLines in count(tokenize(.,  
 ))
  return
    tokenize(.,  
 )[position() gt $numLines -100]

Or:

for $numLines in count(tokenize(.,  
 ))
 return
    subsequence(tokenize(.,  
 ), $numLines -100 +1)

if your xdmp:file-xx is a nature of text file then you could use something like

let $f :=  any file system path 
return fn:tokenize(xdmp:filesystem-file($f),  [

]+ )[ fn:last() - 2 to fn:last()]

here i have used newline & carriage return as my token splitter. if you need something else to tokenize u could. but simple log file tailing then this solution works fine.

given example tails last 2 lines of a given file. if you want more than alter fn:last()-2 to fn:last() - x





相关问题
Why I can t pass two chars as function arguments in C?

I have a function: int get_symbol(tab *tp, FILE *fp, char delim) and I call it like this: get_symbol(tp, fp, ; ) I always have it declared in the header as: int get_symbol(tab *, FILE *, char); ...

problem w/ linking static function g++

I am trying to build a small program and I have my own library libfoo. I have a camera class that is calling a static function from my Vector3 class (i.e. crossProduct). My camera class and Vector3 ...

taking java method names as function arg in clojure

All, I want to create a function that takes a symbol representing a java method and applies it to some object: (user=> (defn f [m] (. "foo" (m))) When I execute this, I get a result much ...

Def, Void, Function?

Recently, I ve been learning different programming langages, and come across many different names to initalize a function construct. For instance, ruby and python use the def keyword, and php and ...

热门标签