的Unix shell - 替换字符串
空白的所有发生的最好的方式,我有一个像的Unix shell - 替换字符串
'abc', '<<some string with space>>', 'xyz'
字符串我希望得到一个字符串象下面这样: -
'abc', '<<some_string_with_space>>', 'xyz'
只需使用awk
:
s="'abc', '<<some string with space>>', 'xyz'"
awk -F', ' '{ gsub(/[[:space:]]+/,"_",$2) }1' OFS=', ' <<<"$s"
输出:
'abc', '<<some_string_with_space>>', 'xyz'
's =“'hello,world'”'? –
@RomanPerekhrest,当字符串在','之间没有空白时它不起作用。 s =“'abc','>','xyz'” –
@gniourf_gniourf,怎么样来详细说明所有可能的输入?我们有一个具体的案例 – RomanPerekhrest
使用awk的gsub和正则表达式\ s来替换空格字符。
mystr = "my sentence is this!"
gsub(/\s/,"_",mystr)
print mystr
我没有downvote,但你应该提到那只是'\ s'的GNU awk - 你需要其他awk' [[:space:]]''。 –
如果你的问题涉及更换空间的广义问题_
里面只有单引号字符串'...'
而不是在其他地方, 我想解决这个使用Perl,按照这样的逻辑:
- 对于输入的每个
'...'
(使用正则表达式:'[^']+'
) - 执行替换所有空间用
_
的函数
像这样:
echo "'abc', '<<some string with space>>', 'xyz'" |\
perl -pe 'sub r { $_ = @_[0]; s/ +/_/g; return $_; }; s/'"'[^']+'"'/r($&)/ge'
您可以使用SED太
echo "'abc', '<<some string with space>>', 'xyz'" | sed s'/ /_/g;s/,_/, /g'
'echo“'hello,world'”|怎么样? sed s'//_/g; s /,_ /,/ g''? –
@gniourf_gniourf,是的,你说得对,如果它总是在>,我们可以使用sed -E':A; s /(
这可能为你工作(GNU SED):
sed ":a;s/^\(\('[^']*',\s*\)*'[^' ]*\) /\1_/;ta" file
或许更安全:
sed ':a;s/^\(\('\''[^'\'']*'\'',\s*\)*'\''[^'\'' ]*\) /\1_/;ta' file
换行符是一个空格 - 您的引用字符串是否可以包含换行符?它可以包含转义引号('\''或'''')吗?它可以包含逗号?你能有一个空的领域吗?目标字符串**真**总是以'>'结尾?花费一些精力来提供简洁,可测试的示例输入和预期的输出,以覆盖您的所有用例,因此我们不会根据您的需求进行猜测。 –