How can I display the contents of a text file on the command line?
Using cat
Since your file is short, you can use
cat
.
cat filename
Using less
If you have to view the contents of a longer file, you can use a pager such as
less
.
less filename
You can make less
behave like cat
when invoked on small files and behave
normally otherwise by passing it the -F
and -X
flags.
less -FX filename
I have an alias for less -FX
. You can make one yourself like so:
alias aliasname='less -FX'
If you add the alias to your shell configuration, you can use it forever.
Using od
If your file contains strange or unprintable characters, you can use
od
to examine the characters. For example,
$ cat file
(ÐZ4 ?o=÷jï
$ od -c test
0000000 202 233 ( 320 K j 357 024 J 017 h Z 4 240 ? o
0000020 = 367 \n
0000023
Even though everybody uses cat filename
to print a files text to the standard output first purpose is concatenating.
From cat's man page:
cat - concatenate files and print on the standard output
Now cat is fine for printing files but there are alternatives:
echo "$(<filename)"
or
printf "%s" "$(<filename)"
The ( )
return the value of an expression, in this case the content of filename which then is expanded by $
for echo
or printf
.
Update:
< filename
This does exactly what you want and is easy to remember.
Here is an example that lets you select a file in a menu and then prints it.
#!/bin/bash
select fname in *;
do
# Don't forget the "" around the second part, else newlines won't be printed
printf "%s" "$(<$fname)"
break
done
For further reading:
BashPitfalls - cat file | sed s/foo/bar/ > file
Bash Reference - Redirecting
Tools for handling text files on unix are basic, everyday-commands:
In unix and linux to print out whole content in file
cat filename.txt
or
more filename.txt
or
less filename.txt
For last few lines
tail filename.txt
For first few lines
head filename.txt