开发者

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 o开发者_如何学运维nly 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), '[\n\r]+')[ 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜