在执行 shell 脚本以检查每行特定位置的特定字符时出错,如果找到,请将其替换为 "X"



我有这个shell脚本。在这个脚本中,我试图在每行的特定位置找到一个字符,如果在该位置找到该字符,则将其替换为"X">

filename = "/ray/test/raymond/test2.data"
if [ -r $filename ]; then
echo " File Found..."
echo " "
fi
cat $filename | 
while read line
do
var = `echo $line | awk '{print substr($0, 422, 1)}'`
if [ "$var" = "D" ]; then
`echo $line | awk '{start = substr ($0, 1, 421); end = substr ($0, 423); print start "X" end}'` >> new_file
else
`echo $line` >> new_file
fi
done

但我得到以下错误,而执行脚本:

/ray/test/raymond$ KSH ray2.shRay2.sh [3]: filename: not found文件发现…

ray2.sh[14]: b: not found

ray2.sh[14]: b: not found

ray2.sh[14]: b: not found

,我不知道为什么。这是在solaris 10

好吧,我将展示两个例子,希望他们能给出一个想法。示例1

filename = "/ray/test/raymond/test2.data"
if [ -f "$filename" -a -r "$filename" ]; then
while read -r line; do
if [ "${line:421:1}" = 'D' ]; then
printf '%s%s%sn' "${line:0:420}" 'X' "${line:422}" >> "$new_file"
else
printf '%sn' "$line" >> "$new_file"
fi
done < "$filename"
elif [ ! -f "$filename" ]; then
echo 'ERROR: Not a file'
return 1
elif [ ! -r "$filename" ]; then
echo 'ERROR: Can not read the file'
return 1
fi

示例2

filename = "/ray/test/raymond/test2.data"
new_file="$filename"'_new.txt'
if [ -f "$filename" -a -r "$filename" ]; then
output="$new_file" awk 'BEGIN { output=ENVIRON["output"] }
{
if(substr($0, 422, 1) == "D") {
$0=sprintf("%s%s%s", substr($0, 1, 421), "X", substr($0, 423))
}
print $0 >> output
}' "$filename"
elif [ ! -f "$filename" ]; then
echo 'ERROR: Not a file'
return 1
elif [ ! -r "$filename" ]; then
echo 'ERROR: Can not read the file'
return 1
fi

相关内容

  • 没有找到相关文章

最新更新