[英]Sed not replacing every occurrence of dot and forward slash
I've got $dir
which holds a string like ./Account/
where the word 'Account' can be any word (eg App, Home, etc).我有
$dir
,它包含一个类似./Account/
的字符串,其中“Account”一词可以是任何词(例如 App、Home 等)。
I want to get rid of the .
我想摆脱
.
and both occurrences of /
to wind up with just Account
.并且两次
/
都以Account
结束。 Here's the pattern I'm using: sed 's/\.\///g'
.这是我正在使用的模式:
sed 's/\.\///g'
。
This is the string I'm applying it on:这是我应用它的字符串:
"import React from 'react';
const $(echo $dir | sed 's/\.\///g') = () => (
<div>
<h1>App</h1>
</div>
);
export default App;"
The .
的
.
and first /
is removed from the output but it still has the second occurrence of the /
.并且第一个
/
从 output 中删除,但它仍然有第二次出现/
。
Output: Output:
import React from 'react';
const Account/ = () => (
<div>
<h1>App</h1>
</div>
);
export default App;
How can I make it so that even the second /
is removed?我怎样才能使第二个
/
被删除?
sed 's/\.\///g'
That removes every ./
, not every .
这会删除每个
./
,而不是每个.
and /
.和
/
。
You want你要
sed 's|[/.]||g'
Using |
使用
|
instead of /
as delimiter is a good idea to avoid the need to escape /
.而不是
/
作为定界符是避免转义/
的好主意。
Example:例子:
$ sed 's|[/.]||g' <<< './Account/'
Account
You may use你可以使用
$(echo $dir | sed 's,\./\([^/]*\)/,\1,g')
The regex delimiters are changed to ,
so as not to have to escape slashes.正则表达式定界符更改为
,
以免必须转义斜杠。
Details细节
\./
- ./
substring \./
- ./
substring\([^/]*\)
- Group 1 (later referred to with \1
placeholder from RHS): any 0 or more chars other than /
\([^/]*\)
- 第 1 组(稍后用 RHS 中的\1
占位符引用):除/
之外的任何 0 个或更多字符/
- a /
char. /
- 一个/
字符。You're searching for the string ./
, whereas you want to be searching for either a .
您正在搜索字符串
./
,而您想要搜索的是.
or a /
.或一个
/
。
Replace the search string with the character class [\/.]
like so:将搜索字符串替换为字符 class
[\/.]
,如下所示:
echo "./Account/" | sed 's/[\/.]//g'
output: output:
Account
Use two substitutions to remove ./
from the beginning and /
from the end of $dir
.使用两个替换从
$dir
的开头/
结尾删除./
。
echo "$dir" | sed 's|^\./||; s|/$||'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.