Shell脚本/ sed表达式,用于在名称中添加/ echo扩展名

时间:2012-04-19 01:02:53

标签: regex shell unix sed

我正在尝试将此示例文件作为输入:

./ chExt1.sh'a b''mouse.ext'

使用当前脚本获取'mouse.a b'作为输出。我遇到的错误是:

~/UnixCourse/scriptAsst> ./chExt1.sh 'a b' 'mouse.dat'
sed: -e expression #1, char 31: unterminated `s' command
a b

mouse.dat
mv: cannot stat `mouse.dat': No such file or directory

我目前的剧本是:

#!/bin/csh                                                                      
set ext="$1"
set oldName="$2"
set newName=`echo "$oldName" | sed 's/\.[A-Za-z0-9][A-Za-z0-9]*$/'.$ext'/g'`
#set newName=`echo "$oldName" | sed 's/\.[A-Za-z0-9][A-Za-z0-9]*$/'.$ext'/g'`   
echo "$ext"
echo "$newName"
echo "$oldName"
mv "$oldName" "$newName"

我错过了哪些文件会使用空格回显扩展名?

由于

2 个答案:

答案 0 :(得分:1)

你需要使用正则表达式吗?如果您只使用:

echo ${2%.*}.$1

你得到相同的结果:

$sh script 'a b' 'test.dat'
test.a b

答案 1 :(得分:0)

.$ext包含空格,因此应将其括在"..."

set newName=`echo "$oldName" | sed 's/\.[A-Za-z0-9][A-Za-z0-9]*$/'".$ext"'/g'`