I have some files containing \n newlines that I am viewing with less. I would like to be able to have less display those newlines as actual newlines.

For example an array:

Array\n(\n    [Color] => Blue\n    [Size] => M\n    [ID] => 123\n    [Questions] => 0\n    [AnotherRandomElement] => 0\n)\n

If the newlines were actually shown as newlines:

    [Color] => Blue
    [Size] => M
    [ID] => 123
    [Questions] => 0
    [AnotherRandomElement] => 0

Obviously much more readable.

I can do this by replacing the chars and pipe into less with something like awk '{gsub("\\\\n","\n")};1' < myfile.txt | less, but it seems like there has to be a way to get less to just do it by itself...

  • less does not interpret \n as newline (or \t as tab for that matter). You will have to preprocess your file.
    – Kusalananda
    Nov 30 '18 at 17:47
  • shouldn't newlines show up as ... new lines? Are those "newlines" actually the two characters \ and n ?
    – Jeff Schaller
    Nov 30 '18 at 17:47
  • @JeffSchaller, Yeah, they apparently aren't "normal" newlines. I'm just getting this string from a print_r($array) in PHP. Nov 30 '18 at 17:54
  • @Kusalananda, if that's true, do you want to post it as an answer? Nov 30 '18 at 17:55
  • Probably not, since there might be a better way of outputting your data from PHP which gets rid of the issue completely, but I don't know that language.
    – Kusalananda
    Nov 30 '18 at 17:57

As far as I know, less doesn't have the option to perform substitution.

As you suggest, the best option is almost certainly going to involve pre-processing then pipe to less. It can still be written fairly elegantly, using sed:

sed <filename> -e 's|\\n|\n|g' | less

This feels risky:

printf "$(< myfile.txt)" | less

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.