码迷,mamicode.com
首页 > 系统相关 > 详细

遍历文件并格式化输出文件(shell脚本实现)

时间:2015-11-14 12:35:20      阅读:392      评论:0      收藏:0      [点我收藏+]

标签:

【背景】
1.项目开发中,急需要根据资源路径res下的文件,生成如下三种格式的文件。
格式一:

#define IDR_CEF_0001    101
#define IDR_CEF_0002    102
...
#define     IDR_CEF_0122    222

格式二:
{“about.html”, IDR_CEF_0001},
{“addProbe.html”, IDR_CEF_0002},

{“img/helpimg/help17.PNG”, IDR_CEF_0122},

格式三:
IDR_CEF_0001 HTML “res\about.html”
IDR_CEF_0002 HTML “res\addProbe.html”
IDR_CEF_0122 HTML “res\img\helpimg\help17.PNG”

【着急情况半手工实现如下】
1.C++实现获取文件名称,输出到txt文档中,拷贝到Excel以便按列处理。
2.构造格式一左数据,组合成格式一数据。
3.结合notepad++正则表达式匹配,构造格式二、三内容,组合成格式二、三数据。

缺点非常明显:
1.手动,很容易路径弄错,文件少弄,后期Bug不可评估。
2.耗时也接近3个小时。
3.如果又有新的文件如(Inner,outer,other)三份资源文件,需要操作3次。
总之,很傻,很笨。

【Shell脚本实现】
源码如下:

#! /bin/bash

function read_dir()
{
for file in `ls $1`
do
if [ -d $1"/"$file ]; then
read_dir $1"/"$file
else
echo $1"/"$file
fi
done
}

#output files
touch out_files.txt
read_dir "/home/laoyang/test/res" > out_files.txt

#recurse files 
#1.delete the front path /home/laoyang
cat out_files.txt | sed ‘s/\/home\/laoyang\///g‘ > out22_files.txt

#get line nums
linenums=`cat out22_files.txt | wc -l`
echo $linenums

#construct format_files.txt
#1.#define IDR_CEF_0001 101
rm -rf format_file1.txt
for((i=1;i<=$linenums;i++)) 
do 
echo "#define   IDR_CEF_"${i}	$[ 100 + ${i} ] >> format_file1.txt
done

#2. {"about.html",  IDR_CEF_0001},
cat out22_files.txt | sed ‘s/test\/res\///g‘ > out33_files.txt
awk ‘{print $2}‘ format_file1.txt > format_file2_1.txt #IDR_CEF_0001 format
sed ‘s/$/},/g‘ format_file2_1.txt > format_file2_2.txt 
sed ‘s/^/{"/g‘ out33_files.txt > out4_file.txt
sed ‘s/$/",/g‘ out4_file.txt > out5_file.txt

paste -d "  " out5_file.txt format_file2_2.txt > format_file2.txt

#3.IDR_CEF_0001 HTML    "res\\about.html"
rm -rf format_file3_2.txt
for((i=1;i<=$linenums;i++)) 
do 
echo "HTML" >> format_file3_2.txt
done

cat out22_files.txt | sed ‘s/test\///g‘ > out44_files.txt
cat out44_files.txt | sed ‘s#\/#\\\\#g‘ > out55_files.txt   

cat out55_files.txt | sed ‘s#^#"#g‘ > out66_files.txt
cat out66_files.txt | sed ‘s#$#"#g‘ > out77_files.txt

paste -d "  " format_file2_1.txt format_file3_2.txt > format_file3_tmp.txt
paste -d "  " format_file3_tmp.txt out77_files.txt > format_file3.txt

mkdir format_rst
mv format_file1.txt format_file2.txt format_file3.txt ./format_rst/

优点:
1.快,不会丢失,有多少文件就是多少文件。
2.可以复用,新增文件或者其他模块也有类似文件,直接跑一遍脚本即可。

Shell脚本在文本逐行读取、按列匹配、正则匹配有先天的优势。所以Shell实现是很好的选择。
如果用C++实现代码行数会几百甚至上千,且匹配会非常复杂。

作者:铭毅天下
转载请标明出处,原文地址:http://blog.csdn.net/laoyang360/article/details/49834859
如果感觉本文对您有帮助,请点击‘顶’支持一下,您的支持是我坚持写作最大的动力,谢谢!

版权声明:本文为博主原创文章,未经博主允许不得转载。

遍历文件并格式化输出文件(shell脚本实现)

标签:

原文地址:http://blog.csdn.net/laoyang360/article/details/49834859

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!