Writing output to files

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Redirection of both standard error and outputHomeAssigns the file descriptor (fd) to file for output →

You need to use the redirection symbol, >, to send data to a file. For example, my script called ./payment.py generate output as follows on screen:

./payment.py -a -t net

Sample outputs:

+-+-----------+---------+-------------+
|#|	Month |	NetRev	| Paid Details|
+-+-----------+---------+-------------+
|1|	Feb-09|	 747.56 | 06-Apr-2009 |
|2|	Mar-09|	 373.14 | 20-Apr-2009 |
|3|	Apr-09|	 163.66 | 19-May-2009 |
|4|	May-09|	 158.18 | 19-Jun-2009 |
|5|	Jun-09|	3768.96 | 17-Jul-2009 |
|6|	Jul-09|	2150.06 | 21-Aug-2009 |
+-+-----------+---------+-------------+

Use the > redirection symbol, to send data to a file called netrevenue.txt, enter:

./payment.py -a -t net >netrevenue.txt

Append Output To Files

Use the >> redirection symbols, to append to a file called netrevenue.txt, enter:

./payment.py -a -t net >>netrevenue.txt

Avoid Overwriting To Files

To disallow existing regular files to be overwritten with the > operator set noclobber option as follows:

echo "Test" > /tmp/test.txt
set -C
echo "Test 123" > /tmp/test.txt

Sample outputs:

bash: /tmp/test.txt: cannot overwrite existing file

To enable existing regular files to be overwritten with the > operator set noclobber option as follows:

cat /tmp/test.txt
set +C
echo "Test 123" > /tmp/test.txt
cat /tmp/test.txt

Reading and Writing From Files

Create a text file called fnames.txt:

vivek
tom
Jerry
Ashish
Babu

Now, run tr command as follows to convert all lowercase names to the uppercase, enter:

tr "[a-z]" "[A-Z]" < fnames.txt

Sample outputs:

VIVEK
TOM
JERRY
ASHISH
BABU

You can save the output to a file called output.txt, enter:

tr "[a-z]" "[A-Z]" < fnames.txt > output.txt
cat output.txt

Notice do not use the same file name for standard input and standard output. This will result into data loss and results are unpredictable.

To sort names stored in output.txt, enter:

sort < output.txt

Finally, store all sorted named to a file called sorted.txt

sort < output.txt > sorted.txt

However,

sort > sorted1.txt < output.txt
← Redirection of both standard error and outputHomeAssigns the file descriptor (fd) to file for output →