我无法正确获取此命令的语法...我需要更改变量包含路径的文件中的变量。
sessionFolderName=/session_`date '+%y%m%d'`_`date '+%H%M'`
sed "s/sessionFolder=.*/sessionFolder=/"$sessionFolder /home/pi/scripts/settings/settings.sh > tmp
mv tmp /home/pi/scripts/settings/settings.sh
但结果是:
sed:-e表达式#1,字符35:未知选项`s'
答案 0 :(得分:2)
问题在于变量开头的/
字符。这会中断sed语法:
[root@ ~]# sed "s/sessionFolder=.*/${sessionFolderName}/" text
sed: -e expression #1, char 21: unknown option to `s'
[root@ ~]# echo $sessionFolderName
/session_170824_0942
如果你使用双反斜杠 - \\ 来逃避它,它可以工作:
[root@ ~]# sed "s/sessionFolder=.*/sessionFolder=\\${sessionFolderName}/" text
sessionFolder=/session_170824_0942
答案 1 :(得分:2)
# You don't need to (and in your case, should not) invoke date command twice.
# Try running following in bash to see the problem.
# $ echo $(date '+%s')_$(sleep 1)_$(date '+%s')
# On a different note, it's better to use $(...) instead of backticks.
sessionFolderName="/session_$(date '+%y%m%d_%H%M')"
# You can use several other separators in sed.
# e.g. :, ;, @, #, _ and even a space
sed "s:sessionFolder=.*:sessionFolder=${sessionFolder}:" /home/pi/scripts/settings/settings.sh > tmp
mv tmp /home/pi/scripts/settings/settings.sh
Refer to this关于使用$()
而不是反引号
答案 2 :(得分:1)
1)您需要转义输入中的/
2)修改sed命令的格式,如下所示
sessionFolderName=\\/session_`date '+%y%m%d'`_`date '+%H%M'`
sed "s/sessionFolder=.*/sessionFolder="$sessionFolderName"/" /home/pi/scripts/settings/settings.sh > tmp