新建文件 conv_to_utf8.sh

#!/bin/bash

function conv_file_to_utf8() {
    local file="$1"
    encoding=`file -I ${file} | awk -F= '{print $2}'`
    # echo "encoding: $encoding"
    if [[ "$encoding" != *"utf-8"* ]]; then
        encoding="gbk" # 这里需要根据原始编码改一下,一般都是gbk或者gb2312的转utf8
        iconv -f "$encoding" -t UTF-8 "$file" > "${file}.utf8.tmp"
        if [ $? -eq 0 ]; then
            # echo "命令执行成功"
            mv "${file}.utf8.tmp" "${file}"
            echo -e "\033[32mconver $file $encoding -> utf8 success\033[0m"
        else
            rm "${file}.utf8.tmp"
            echo -e "\033[31mconver $file $encoding -> utf8 fail!!!!\033[0m"
        fi
    else
        echo "$file is already in UTF-8 encoding."
    fi
}


function query() {
    read -p "$1请输入Y/n: " input
    case $input in
        [Yy])
            # echo "你输入了Y或y"
            ;;
        *)
            echo "你取消了操作"
            exit
            ;;
    esac
}

if [ -z "$1" ]; then
    echo "参数为空,请填写后缀类型,调用方式如: bash conv_to_utf8.sh txt"
else
    path=`pwd`
    sufx=$1
    echo '将遍历并转换目录"'$path'"下的".'$sufx'"文件,确定继续吗?'
    query "操作不可逆,建议做好备份,确定要替换吗?"
    query "操作不可逆,请再次确定要替换吗?"
    for entry in `find . -type f -name "*.$sufx"`; do
        # echo $entry
        conv_file_to_utf8 "$entry"
    done
fi

打开终端,进入到需要批量修改的文件目录,执行下面的命令并继续输入两次Y,可以批量将".c"文件编码改为utf8。
bash xxxx/conv_to_utf8.sh c

image.png


RobinTang
3.9k 声望37 粉丝