I'm wondering what some of the escape sequences do including the following:
\b backspace
\f form feed
\n new line
\r carriage return
\t tab
Also, what is the difference between form feed, new line, and carriage return? What is the difference between \t and a space? They all look the same...
\n is a line feed (LF) character, character code 10. \r is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF).
They're different characters. \r is carriage return, and \n is line feed.
\n is used for the newline or linefeed, whereas \r is the carriage return.
\n means new line. It means that the cursor must go to the next line. \r means carriage return. It means that the cursor should go back to the beginning of the line.
You can test these escape sequences using printf
, for example in a C program or using a Unix/Linux shell such as Bash as shown below.
printf
is much more reliable because use of tabs can still result in staggered columns. See an example at the bottom of this answer.The $
represents the shell prompt and should not be typed. It is included in order to differentiate between what you type and what is output. I've included a newline \n
at the end of each string so the output occupies its own line.
$ printf 'help\blo - backspace\n'
hello - backspace
$ printf 'two\nlines - newline\n'
two
lines - newline
$ printf 'clocks - carriage return\rsla\n'
slacks - carriage return
$ printf 'Fruit\tColor\tQuantity\ngrapes\tgreen\t100\nbananas\tyellow\t50\n- tabs\n'
Fruit Color Quantity
grapes green 100
bananas yellow 50
- tabs
Please see ASCII Control Characters for more information.
Try this to see how printf
formatting can be an improvement over tabs:
$ array=(A B C 'apple pie' 'banana split' 'cherry turnover' 100 200 300)
$ for ((i=0; i<12; i+=3)); do printf '%s\t%s\t%s\n' "${array[@]:i:3}"; done
A B C
apple pie banana split cherry turnover
100 200 300
$ for ((i=0; i<12; i+=3)); do printf '%-16s%-16s%s\n' "${array[@]:i:3}"; done
A B C
apple pie banana split cherry turnover
100 200 300
As you can see, the columns aren't staggered in the second version and overall the output is the same width.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With