创建与读写
文件基础操作
空文件创建
要创建空文件,请使用以下语法:
> newfile.name
#!/bin/bash
TAR=/bin/tar
# SCSI tape device
TAPE=/dev/st0
# Backup dir names
BDIRS="/www /home /etc /usr/local/mailboxes /phpjail /pythonjail /perlcgibin"
# Logfile name
ERRLOG=/tmp/tar.logfile.txt
# Remove old log file and create the empty log file
>$ERRLOG
# Okay lets make a backup
$TAR -cvf $TAPE $BDIRS 2>$ERRLOG
注意,您还可以使用
touch /tmp/newtextfile
文件写入
您需要使用重定向符号
./payment.py -a -t net >netrevenue.txt
使用
./payment.py -a -t net >>netrevenue.txt
要禁止使用
echo "Test" > /tmp/test.txt
set -C
echo "Test 123" > /tmp/test.txt
要使用
cat /tmp/test.txt
set +C
echo "Test 123" > /tmp/test.txt
cat /tmp/test.txt
先读后写
创建一个名为
vivek
tom
Jerry
Ashish
Babu
现在,按如下所示运行
tr "[a-z]" "[A-Z]" < fnames.txt
样本输出:
VIVEK
TOM
JERRY
ASHISH
BABU
您可以将输出保存到名为
tr "[a-z]" "[A-Z]" < fnames.txt > output.txt
cat output.txt
注意,对于标准输入和标准输出,请不要使用相同的文件名。这将导致数据丢失,并且结果是不可预测的。要对存储在
sort < output.txt
最后,将所有已排序的命名存储到名为
sort < output.txt > sorted.txt
sort > sorted1.txt < output.txt
指定输出文件的fd
文件描述符
exec fd> output.txt
创建一个名为
#!/bin/bash
# Let us assign the file descriptor to file for output
# fd # 3 is output file
exec 3> /tmp/output.txt
# Executes echo commands and # Send output to
# the file descriptor (fd) # 3 i.e. write output to /tmp/output.txt
echo "This is a test" >&3
# Write date command output to fd # 3
date >&3
# Close fd # 3
exec 3<&-
要将文件描述符分配给输入文件,请使用以下语法:
exec fd< input.txt
创建一个名为
#!/bin/bash
# Let us assign the file descriptor to file for input
# fd # 3 is Input file
exec 3< /etc/resolv.conf
# Executes cat commands and read input from
# the file descriptor (fd) # 3 i.e. read input from /etc/resolv.conf file
cat <&3
# Close fd # 3
exec 3<&-