---
title: "将数据导出成为文本格式的备份的shell脚本"
author: "luogen33"
date: "2011-06-06T23:48:34Z"
tags: []
categories: ["数据库"]
slug: "shell"
draft: false
lastmod: "2011-06-06T23:58:10Z"
id: 1071163
url: "https://luogen33.iteye.com/blog/1071163"
---

提示： #将中表的内容导出成为一个文本格式的shell脚本 #有两种使用方法（假设这个脚本的名字叫做unload): #1.将一个用户中所有的数据库
#将中表的内容导出成为一个文本格式的shell脚本 
#有两种使用方法（假设这个脚本的名字叫做unload): 
#1.将一个用户中所有的数据库表的内容到出来： 
unloaduserid/passwd 
#2.只导出一个表的内容： 
#unloaduserid/passwdtable_name 
#这里要感谢you的帖子，是他让我学会了如何设置sqlplus环境，从而 
#将数据库数据分解出来。 
# 
#我还想写出一个根据数据库中的数据字典的内容自动生成ctl文件的脚本， 
#以便于将文本的数据库内容使用sqlldr导入到数据库中 
#请各位提示我可能要涉及的数据字典是哪些：） 
# 

sep=‘，‘#--分隔符，可以修改成自己想要的分隔符，如‘‘ 
load_table 

if;then 
echo"Usage:$0<userid/passwd@connection><table_name>" 
exit 
echo“c"Userid:" 
readuserid1 
echo“c"Passwd:" 
echooff 
readpasswd 
userid=$userid1$passwd 
echoon 
else 
userid=$1 
fi 

if;then 
load_table; 
if];then 
echo"notableinuser$userid" 
exit 
fi 
else 
tables=$2 
fi 

fortablein$tables 
do 
rm-fwk_$table.txt 
echo"setcolsep$sep; 
setechooff; 
setfeedbackoff; 
setheadingoff; 
setpagesize0; 
setlinesize1000; 
setnumwidth12; 
settermoutoff; 
settrimouton; 
settrimspoolon; 
spoolwk_$table.txt; 
selectfrom$table; 
spooloff; 
"sqlplus$userid>/dev/null 
if;then 
echoerror:sqlplus$useriderrorinunloadtable$table!! 
echopleasecheckuseridandpasswdordatabase. 
exit 
fi 

if] 
then 
catwk_$table.txtgrep-v"^SQL>">$table.txt 
sed-e"s/$//g"$table.txt>wk_$table.txt 
mvwk_$table.txt$table.txt 
if];then 
echo"unloadtable$table....ok" 
else 
cat$table.txt 
err="$err$table" 
fi 

else 
echo$0error 
fi 
done 
if];then 
echounloadcomplete! 
else 
echo"unloadtable$errerror，pleasecheckit!" 
fi







  例如:

    表 TEST1(ORACLE数据库  用户名USER,密码123)
    表中记录为  1223       555         5555       5555
                       2222      555         4555        448
                          :           :               :              :
                          :           :               :              :
   装载到/USR/TEST/TEXT.TXT文件中
   文件中各字段之间用逗号(‘,’)分割，行间用MS-DOS回车换行符分隔
   如上 应记录为
                      1223，555，5555，5555
                      2222，555，4555，448
                      ......

试一下这个脚本。
#myexport.sh

sqlplus username/passwd@dbinstance <<!
SET NEWPAGE 0
SET SPACE 0
SET PAGESIZE 0
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
spool temp
SELECT * from test;
spool off
!

awk '$0 !~ /SQL|^$/{for(i=1;i<NF;i++) printf $i",";printf $NF"\n"}' temp.lst >/USR/TEST/TEXT.TXT