首页 > 解决方案 > How do I write a file path which include a regular expression

问题描述

Depending on the system I am working on, there might be 2 different possible paths (mutually exclusive):

System1: /tmp/aword/foo
System2: /tmp/bword/foo

I am supposed to echo something into the foo file regardless of which system I encounter (through a shell script).

How do I include a regular expression within the path itself, to take the correct (existent) path?

somethings I have tried:

#doesn't work
echo Hello > /tmp/(a|b)word/foo
#doesn't work
echo Hello > /tmp/[a|b]word/foo

is there a way of doing this without having to include a test before this which tests for path existence?

标签: linuxshell

解决方案


如果字面上是awordbword并且您知道其中只有一个存在,则可以使用

echo 'Hello' > /tmp/[ab]word/foo

这是一个 shell 模式,记录在 Bash 手册POSIX sh 规范中。

但是,如果两条路径都存在,Bash 将抱怨

-bash: [ab]word: ambiguous redirect

推荐阅读