前言
最近一直在写php和c代码,好久没动bash脚本,一些命令有些生疏了,今天有个需求要对指定目录下的文件进行字符编码转换,写了个脚本实现了一下
目录结构
/home/wzy/Downloads/execl/
|__科学/{1.csv,2.csv,3.csv,4.csv}
|__教育/{1.csv,2.csv,3.csv,4.csv}
|__生活/{1.csv,2.csv,3.csv,4.csv}
|__体育/{1.csv,2.csv,3.csv,4.csv}
需求
遍历指定根目录下的所有文件,进行文件编码的转换
技巧
1.bash shell中for循环的使用
2.iconv字符编码转换工具的使用
脚本代码
#!/bin/bash
#1.变量定义
directory="/home/wzy/Downloads/execl"
f_encoding="utf-8"
t_encoding="gbk"
#2.遍历子目录
for dir in `ls $directory`
do
if [ -d $directory/$dir ]
then
#3.遍历子目录的文件
for file in `ls $directory/$dir`
do
if [ -e $directory/$dir/$file ]
then
#4.文件类型转换
iconv -f $f_encoding -t $t_encoding $directory/$dir/$file -o $directory/$dir/iconv.$file
#5.删除原始文件
if [ $? -eq 0 ]
then
rm $directory/$dir/$file
fi
fi
done
fi
done
iconv命令
语法
iconv -f [encoding] -t [encoding] [inputfile] -o [outputfile]
选项
-f : 原文件编码
-t : 需要转换的编码
-o : 指定输出文件
后记
记录这个脚本主要是吃饭前对脚本中绝对路径的使用错误一直没有发现,团队喝酒归来后反而头脑清醒,搞定了,希望对各位看我博客的同学也有所帮助,欢迎交流,一般有留言我都会回复的,共同学习,共同进步!
分享到:
相关推荐
在将windows上的jsp网页移植到linux环境中时,发现一个个的转换编码及修改默认编码类型太慢,写此脚本进行尝试文件遍历~ 好久不写,手生了。 代码如下: #!/bin/bash # # SPATH=”/root/chengji/WebRoot” DPATH=”/...
在linux 下的用c实现的遍历指定文件夹下的所有文件,并读出文件中的内容
用shell写的递归遍历目录的脚本,脚本实现递归遍历指定目录,打印目录下的文件名。 实例1: 代码如下:#!/bin/shfunction scandir() { local cur_dir parent_dir workdir workdir=$1 cd ${workdir} if [ ${...
主要是一份bash shell 4.2 的源码,共享给大家
Bash Shell 管理Linux
bash shell高级编程
Bash Shell 编程高级教程 (中文版)
Cameron Newham and Bill Rosenblattham 《Learning the bash shell》是比较好的一本入门级经典教材,学linux shell 的不妨下来看看,不过是英文版的。
Bash shell编程参考手册,Linux编程必备。
学习Bash Shell的经典教材,推荐
Learning the bash Shell, 3rd Edition This refreshed edition serves as the most valuable guide yet to the bash shell. It's full of practical examples of shell commands and programs guaranteed to ...
bash shell
实验十二 Bash Shell相关指令练习
《Learning the bash Shell,3rd Edition,by Cameron Newham》, bash 的权威指南,本书中文版本下载地址:http://download.csdn.net/source/2244004。内容预览: Chapter 1. bash Basics Chapter 2. Command-Line ...
bash,shell模版 语法 设置文件
简单的Bash脚本到Windows批处理文件转换器将bash脚本( *.sh )转换为Windows批处理文件( *.bat )。 这不应该是一个完全完整/正确的工具,而是转换脚本时的起点。 对于简单的脚本,这可能会创建正确的结果。 在线...
learn bash shell~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
linux bash shell脚本文件.sh,自动输入sudo的密码 在脚本中使用sudo命令,将密码保存在脚本中,不需要手动输入密码
Learning the bash Shell(中文版第二版)