创建名称包含“/”和“ ' ”的文件夹

创建名称包含“/”和“ ' ”的文件夹

mkdir我正在根据变量建立文件路径(并对其进行调整):

mkdir "$root_folder/$title ($year)"

我遇到过 $title 为 的情况9/11: Inside the President's War Room/是一个问题,因为 mkdir 会将其解释为文件夹路径。所以我想用 替换所有,/以便\/mkdir 按字面意思理解它,而不是认为它是路径。'名称中的 也会出现问题。所以我也想用 替换所有,'但这\'比我想象的要难。

我的最终目标是以这样的方式制作文件夹,以便这些文件夹/能够'被逐字解释。我已经尝试过以下方法:

title=$(echo "$title" | sed -e "s|'|$(echo "\\")\'|g")
${title/\//\\/}
#---
title=$(echo "$title" | sed -e "s|'|$(echo "\\")\'|g" -e "s|/|\\/|g")
$title
#---
mkdir "$root_folder/'$title ($year)'"

答案1

只要您始终正确引用变量,单引号或双引号就不会引起任何问题。

$ title=$(cat << END_TITLE
This "is a title" with 'two kinds of quotes'
END_TITLE
)

$ declare -p title
declare -- title="This \"is a title\" with 'two kinds of quotes'"

$ mkdir "$title"      # no need to try to force extra quotes in here

$ echo $?
0

文件名不得包含一个/字符,无论您如何努力尝试将其转义。斜线是目录分隔符。您必须替换其他字符。假设您选择-

mkdir "$root_folder/${title//\//-} ($year)"

使用 bash 的Shell 参数扩展而不是调用 sed。

相关内容