Viewing files and searching text

Linux · Essentials · 9 min

Reading configs and logs is most of what troubleshooting a server looks like.

Choose the viewer by file size and purpose:

  • cat file prints a small file in one go,
  • less file pages through anything, however large: Space and b to move, /text to search, n for the next match, G for the end, q to quit,
  • head -n 20 and tail -n 20 show the beginning or end,
  • tail -f app.log follows a file, printing new lines as they are written; tail -F keeps following across log rotation.

grep pattern files prints matching lines. Common flags: -i ignore case, -n line numbers, -r recursive through directories, -v invert (lines that do not match), -c count, -l only file names, -E extended regexes, -C 3 three lines of context. Combine them with pipes: grep -v '^#' sshd_config | grep -v '^$' shows a config without comments and blank lines.

wc -l counts lines, file identifies what a file actually contains (text, ELF binary, gzip...), and diff a b compares two files. Compressed logs can be read without unpacking using zcat, zless and zgrep.

Do not cat binary files or huge logs into the terminal; use less or head. Files you cannot read give "Permission denied", which often means you need sudo.

Example

cat /etc/hostname                 # print a small file
less /var/log/syslog              # page: / search, n next, G end, q quit
head -n 3 /etc/passwd             # first 3 lines
tail -n 20 /var/log/nginx/error.log
tail -F /var/log/nginx/access.log # follow new lines, survive rotation
wc -l /etc/passwd                 # 32 /etc/passwd
grep -n '^root' /etc/passwd       # 1:root:x:0:0:root:/root:/bin/bash
grep -ri 'timeout' /etc/nginx/    # recursive, case-insensitive
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'   # config without comments
grep -c ' 500 ' access.log        # count server errors
zgrep 'error' /var/log/syslog.2.gz
file /usr/bin/ls                  # ELF 64-bit LSB pie executable, x86-64 ...

Remember

  • less for big files, head/tail for ends, tail -f to follow
  • grep -i -n -r -v -c cover most searches
  • zcat, zless and zgrep read compressed logs

Watch out for

  • Opening a multi-gigabyte log with cat or a text editor instead of less or tail.

Check yourself

  1. Which command shows new log lines as they are written?
  2. What does `grep -v '^#' file` output?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man7.org/linux/man-pages/man1/tail.1.html