Using readFile to read a reduced set of lines


I have a question regarding the readFile function.

First, the context

According to the Hugo documentation, the readfile function can be used to obtain the content of a file as a string. Like so:

{{readFile "README.txt"}} ā†’ "Hugo Rocks!"

However by default the readFile function reads the whole content of the file, and I wish I could restrict it by specifying the first and last lines of the file to read.

Here is an example of what Iā€™d like to have

We have a file README.txt:

Hugo Rocks!
Hugo's fast!
Hugo is open source!
Hugo uses Markdown!

Then use it like that:

{{readFile "README.txt" 2 4 }} ā†’ "Hugo's fast!\nHugo is open source!\nHugo uses Markdown!"

So my question is:

Do you know how I can perform that? Even without using readFile.

Thank you,
Remi Andruccioli

1 Like
{{ $file := readFile "README.txt" }}

{{/* Splitting content by newline */}}
{{ $file := split $file "\n" }}

{{/* Limit the array/slice,  start from 2nd item then grab all first 3 item */}}
{{ $file := first 3 (after 1 $file) }}

{{/* Delimit by newline */}}
{{ $file := delimit $file "\n" }}

{{ $file }}

References: Split, Delimit, First, After

1 Like

Thank you SO much!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.