如何使用Unix将文件名中的特殊字符替换为下划线符号?

2024-04-25 01:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理这个任务,在unix/Python的所有递归文件夹中,我需要将文件名中的特殊字符替换为u

PFB是Unix代码

#!/bin/sh
 # Shell script to find out all the files under a directory and
 #its subdirectories. This also takes into consideration those files
 #or directories which have spaces or newlines in their names

DIR="."

function list_files()
{
 if !(test -d "$1")
 then echo $1; return;
fi

function rename_files()
{
    str="$1"

    regex="[0-9a-zA-Z]._+"
    if [[ ! "$str" =~ ^[0-9a-zA-Z]+$ ]]
    then
       echo $1
    else
       echo "f you"
    fi
}

cd "$1"
# echo; echo `pwd`:; #Display Directory name

 for i in *
 do
 if test -d "$i" #if dictionary
 then
 list_files "$i" #recursively list files
cd ..
 else
 # echo "$i"; #Display File name
 rename_files "$i"
fi

 done
}

有人能帮我用代码将文件名中的字符替换为u吗

例如,如果文件名为ABC$XYZ*PQR.xls,则应将其重命名为ABC_XYZ_PQR.xls

必须对文件夹及其子文件夹中的所有文件执行此过程

请帮忙


Tags: or代码intestecho文件夹if文件名
2条回答

在正则表达式的括号子表达式中,插入符号(^)充当否定,即括号中的字符而不是。例如

echo 'ABC$XYZ*PQR.xls' | sed 's/[0-9a-zA-Z._]/_/g'

将产生以下代码“___$___*_______

echo 'ABC$XYZ*PQR.xls' | sed 's/[^0-9a-zA-Z._]/_/g'

将产生“ABC_XYZ_PQR.xls”。您可以修改后一个代码,以便在rename_files()函数中使用

:>echo 'ABC$XYZ*PQR.xls' | sed 's#[^[:alnum:]|\.]#_#g' 
ABC_XYZ_PQR.xls
:>

相关问题 更多 >