文件编码方式批量转换

脚本formatCH.sh

#!/bin/bash

if [ $# != 1 ]
then
	echo "must with target file"
	exit
fi


dos2unix $1

##去除行末的空格与制表符
sed  's/[ \t]*$//g' <$1  > $1_f1

mv $1_f1 $1

上述脚本虽然删除了行尾空格,但会在文件尾部带来^@
自写一个工具解决此问题

#include <stdio.h>

int getlastline(FILE* fp, char buf[1024])
{
	
	while(!feof(fp))  
	{
		fgets(buf,sizeof(buf),fp); 
		if(feof(fp))    
			break;
	}

	return 0;
}


int findenterkey(FILE *fp)
{
	char tmpbuf[1];
	int keycnt=0;
	long offset;
	fseek(fp,0,SEEK_END);
	offset = ftell(fp);
	while(1) {
		offset--;
		fseek(fp,offset,SEEK_SET);
		fread(tmpbuf,1,1,fp);
		if (tmpbuf[0] == '\n') {
			keycnt++;
			if(keycnt == 2) {
				break;
			}
		}
	}
	return offset+1;
}

int main(int argc, char *argv[])
{
	if(argc < 2) {
		printf("please input target file \n");
		return -1;
	}
	
	FILE* fp = fopen(argv[1], "a+");
	int fd;
	char buf[1024];
	long offset;
	getlastline(fp, buf);
	printf("%s\n",buf);
	if (buf[0] == 0 && buf[1]==0 ) {
		printf("%s is unformat file,will delete last line \n");
		offset = findenterkey(fp);
		printf("will inset EOF on seek %ld \n", offset);
		fd = fileno(fp);
		ftruncate(fd, offset);	
}
	
	fclose(fp);

	return 0;
}


在linux下运行脚本encode_convert.sh

#!/bin/bash

for f in `find $1 -name "*.[ch]"`
do
	encode=`file $f | awk '{print $4}'`
	echo "encode = $encode"	
	if [ $encode == "ISO-8859" ]
	 then
		iconv -f GBK -t UTF-8 $f  -o ${f}_utf8	
		rm $f
		mv ${f}_utf8 $f
	fi
	
	dos2unix $f
	##去除行末的空格与制表符
	sed  's/[ \t]*$//g' <$f  > ${f}_f1
	mv ${f}_f1 $f

done


完美解决中文乱码问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xxgui1992

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值