如何在一个变量
问题描述:
好一天的值代入,如何在一个变量
我有一个简单的UNIX脚本test.sh
我需要替换变量的值。 此变量包含一个目录路径。
我test.sh脚本
#!/bin/sh
filepath="/host/messages/in/documents"
archivePath=`${filepath/\/in/\/archive/}`
echo "archive path is " $archivePath
我得到一个 “坏替代” 错误,当我运行它。
为archivePath所需的输出应该是:
/host/messages/archive/documents
什么我做错了,这可能是一个可能的解决方案?
答
必须使用bash(或ksh或zsh的),使用正确的语法${varname/pattern/replacement}
和pattern
和replacement
逃避\
/
。
#!/bin/bash
filepath="/host/messages/in/documents"
archivePath="${filepath/\/in\//\/archive\/}"
echo "archive path is $archivePath"
答
发现sed的一个解决方案:
#!/bin/sh
filepath="/host/messages/in/documents"
echo $filepath | sed -e %s/in/archive/g
archivePath=`echo $filepath | sed -e s/in/archive/g`
echo "archive path is $archivePath"
错误:不读shell的手册页。解决方案:阅读shell的手册页。请记住,并非所有的世界都是一场暴躁。替代不是POSIX shell的一个特性,它是其他一些shell的扩展(想起bash和zsh)。注意:反引起**过程替换**,而不是**参数替换**。 – Jens
如果不能替代,那么我该如何将'in'替换为'archive'?. – Chor419