简体   繁体   English

如何删除awk中的转义字符?

[英]How to remove escape character in awk?

I am trying to concat two strings in awk. 我试图用awk连接两个字符串。 One of them seems to contain '\\r': 其中之一似乎包含'\\ r':

stringA = "Hello\r"
stringB = "Hi"
print stringA stringB

results in 结果是

Hillo

What can I do to remove the '\\r' if I can't change the source of stringA? 如果无法更改stringA的来源,该怎么办才能删除'\\ r'?

Thanks :) 谢谢 :)

Given: 鉴于:

$ awk 'BEGIN {s1="Hello\r"; s2="Hi"; print s1 s2}'
Hillo

Just replace the carriage return \\r with gsub() : 只需用gsub()替换回车符\\r

$ awk 'BEGIN {s1="Hello\r"; s2="Hi"; gsub(/\r$/,"",s1); print s1 s2}'
HelloHi

That is, gsub(/\\r$/,"",s1) looks for the \\r at the end of the string s1 and replaces it with "" , that is, it removes it. 也就是说, gsub(/\\r$/,"",s1)在字符串s1的末尾查找\\r并将其替换为"" ,即将其删除。

If multiple carriage returns appear, just get rid of the $ so that it doesn't just match the one at the end of the line. 如果出现多个回车符,则删除$ ,使其不与行尾的$匹配。

Ed Morton suggests in comments that probably just one carriage return will appear in a string, which is quite reasonable. 埃德·莫顿(Ed Morton)在评论中建议,字符串中可能只会出现一个回车符,这是非常合理的。 If this is the case, just use sub() instead: sub(/\\r$/,"",s1) . 如果是这种情况,只需使用sub()sub(/\\r$/,"",s1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM