- Linux Shell Scripting Cookbook(Third Edition)
- Clif Flynt Sarath Lakshman Shantanu Tushar
- 178字
- 2021-07-09 19:46:12
Line numbers
The cat command's -n flag prefixes a line number to each line. Consider this example:
$ cat lines.txt line line line $ cat -n lines.txt 1 line 2 line 3 line
The cat command never changes a file. It sends output to stdout after modifying the input according to the options. Do not attempt to use redirection to overwrite your input file. The shell creates the new output file before it opens the input file. The cat command will not let you use the same file as input and redirected output. Trying to trick cat with a pipe and redirecting the output will empty the input file.
$> echo "This will vanish" > myfile $> cat -n myfile >myfile cat: myfile: input file is output file $> cat myfile | cat -n >myfile $> ls -l myfile -rw-rw-rw-. 1 user user 0 Aug 24 00:14 myfile ;# myfile has 0 bytes
The -n option generates line numbers for all lines, including blank lines. If you want to skip numbering blank lines, use the -b option.