《懒人Shell脚本》之一——遍历文件并格式化输出文件

【背景】
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
如果感觉本文对您有帮助,请点击‘顶’支持一下,您的支持是我坚持写作最大的动力,谢谢!

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铭毅天下

和你一起,死磕Elastic!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值