正则表达式 – Bash Script sed命令与通过命令行传递的文件无法
问题
当我试图根据一些正则表达式要求编写一个重命名海量文件的脚本时,我的iTerm2上的命令正常工作成功,但同样的命令无法在脚本中完成工作. 另外我的一些文件名包括一些中文和韩文字符.(不知道是不是这个问题) 码 所以我的代码有三个输入:旧正则表达式,新正则表达式和需要重命名的文件. 这不是代码: #!/bin/bash # we have less than 3 arguments. Print the help text: if [ $# -lt 3 ] ; then cat << HELP ren -- renames a number of files using sed regular expressions USAGE: ren 'regexp' 'replacement' files... EXAMPLE: rename all *.HTM files into *.html: ren 'HTM' 'html' *.HTM HELP exit 0 fi OLD="$1" NEW="$2" # The shift command removes one argument from the list of # command line arguments. shift shift # $@ contains now all the files: for file in "$@"; do if [ -f "$file" ] ; then newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"` if [ -f "$newfile" ]; then echo "ERROR: $newfile exists already" else echo "renaming $file to $newfile ..." mv "$file" "$newfile" fi fi done 我在.profile中注册bash命令: alias ren="bash /pathtothefile/ren.sh" 测试 原始文件名是“?01?.mp3”,我希望它成为“第01课.mp3”. 所以用我的脚本我用: $ren "?([0-9]*)?" "第1课" *.mp3 而且似乎脚本中的sed没有成功运行. 但以下完全相同,可以取代名称: $echo "?01?.mp3" | sed s/"?([0-9]*)?.mp3"/"第1课.mp3"/g 有什么想法吗?谢谢 打印结果 我在脚本中进行了以下更改,以便它可以打印进程信息: newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"` echo "The ${file} is changed to ${newfile}" 我的测试结果是: The ?01?.mp3 is changed into ?01?.mp3 ERROR: ?01?.mp3 exists already 所以没有格式问题. 更新(全部在bash 4.2.45(2),Mac OS 10.9下完成) 测试 当我尝试直接从bash执行命令时.我的意思是for循环.有一些有趣的东西.我首先使用以下命令将所有名称存储到files.txt文件中: $ls | grep mp3 > files.txt 做sed和bla bla.而在bash交互模式下的单个命令如下: $file="?01?.mp3" $echo $file | sed s/"?([0-9]*)?.mp3"/"第1课.mp3"/g 给 第01课.mp3 而在下面的交互模式中: files=`cat files.txt` for file in $files do echo $file | sed s/"?([0-9]*)?.mp3"/"第1课.mp3"/g done 没有变化! 到现在为止: echo $file 得到: $?30?.mp3 (只有30个文件) 问题部分 我尝试了之前工作的第一个命令: $echo $file | sed s/"?([0-9]*)?.mp3"/"第1课.mp3"/g 它没有给出任何变化: $?30?.mp3 所以我创建了一个新的新文件并再次尝试: $newfile="?30?.mp3" $echo $newfile | sed s/"?([0-9]*)?.mp3"/"第1课.mp3"/g 它给出了正确的: $第30课.mp3 WOW ORZ …为什么!为什么!为什么!我试着看看文件和新文件是否相同,当然,它们不是: if [[ $file == $new ]]; then echo True else echo False fi 得到: False 我猜 我想有一些编码问题,但我发现没有参考,有人可以帮忙吗?谢谢了. 更新2 我似乎明白字符串和文件名之间存在巨大差异.具体来说,我直接使用如下变量: file="?30?.mp3" 在脚本中,sed工作正常.但是,如果变量是从$@传递的,或者将变量设置为: file=./*mp3 然后sed无法工作.我不知道为什么.顺便说一下,mac sed没有-r选项,在ubuntu -r中没有解决我上面提到的问题. 解决方法
一些错误合并:
>为了在正则表达式中使用组,您需要在sed中使用扩展的regex -r,在grep中使用-E 例 files="?2?.mp3 ?30?.mp3" for file in $files do echo $file | sed -r 's/?([0-9]*)?.mp3/第1课.mp3/g' done 输出 第2课.mp3 第30课.mp3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |