[英]sed: replace a space at specific position
I'd like to replace a space character in position 4 of "abc "
, other characters at that position should be left untouched. 我想替换位置
"abc "
中第4个空格字符,应保持该位置上的其他字符不变。 Matching only for a space doesn't seem to work: 仅匹配一个空格似乎不起作用:
$ echo "abc " | sed "s/\ /d/4"
abc
Matching with .
与匹配
.
seems to do it, but it's matching too broad for my case: 似乎可以做到,但是对于我来说,它的匹配范围太广了:
$ echo "abc " | sed "s/./d/4"
abcd
Am I missing a detail about sed
, or its regex flavor? 我是否缺少有关
sed
或regex风格的详细信息?
You could use range quantifier \\{min,max\\}
or \\{num\\}
. 您可以使用范围量词
\\{min,max\\}
或\\{num\\}
。
$ echo "abc " | sed 's/^\(.\{3\}\) /\1d/'
abcd
^
Asserts that we are at the start. ^
断言我们是开始。 \\(..\\)
called capturing groups. \\(..\\)
称为捕获组。 .\\{3\\}
matches exactly three character, those three characters are captured by the group index 1. Later we could refer those captured characters by back-referencing. .\\{3\\}
完全匹配三个字符,这三个字符由组索引1捕获。稍后,我们可以通过反向引用引用这些捕获的字符。
You're trying to replace the 4th instance of space, which in this case it isn't. 您正在尝试替换空间的第4个实例,在这种情况下不是。
echo "abc " | sed "s/ /d/"
If there were at least 4 spaces in your text, it would work. 如果您的文字中至少有4个空格,则可以使用。
Edit: If you need to replace the 4th character you can do this: echo "abc " | sed "s/./d/4"
编辑:如果您需要替换第四个字符,您可以这样做:
echo "abc " | sed "s/./d/4"
echo "abc " | sed "s/./d/4"
This means "replace the 4th instance of any character with d". 这意味着“用d替换任何字符的第4个实例”。
Another way of doing it with perl
: 使用
perl
另一种方法:
echo "abc " | perl -pe 's/...\K /d/'
abcd
Ps. PS。
\\K
is positive look-behind. \\K
是正向后看。
If you want to replace it then. 如果要更换它。
$ echo "abc " |sed -r 's/ /d/1'
The above command will search for the 1st occurrence of space character and replace it with d
, for your case you can replace it with any thing you want. 上面的命令将搜索第一个出现的空格字符,并将其替换为
d
,根据您的情况,您可以将其替换为所需的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.