将行尾的空格字符替换为特定字符串
我正在处理具有 6 个字段的空格分隔文件:
Pop1 ID60776 62 C 10 62
Pop1 ID62442 13 A 2 13
Pop1 ID63614 56 C 0
Pop1 ID67511 61 T 37 61
Pop1 ID68222 51 A 0
Pop1 ID68407 65 C 16 65
但是,在第 3 行和第 5 行中,只有 5 个字段。在这些情况下,字段 5 中的 0 后跟空格字符 ('0')。
我想在行尾找到空格字符的所有实例(即 \s$ )并将其替换为空格 NA (即 '\sNA'),但我在这样做时遇到了真正的麻烦。例如,我尝试过 sed:
sed s/\\s$/\\sNA/g
但它不起作用。有人可以帮我吗?
谢谢你!
I'm dealing with space delimited file with 6 fields:
Pop1 ID60776 62 C 10 62
Pop1 ID62442 13 A 2 13
Pop1 ID63614 56 C 0
Pop1 ID67511 61 T 37 61
Pop1 ID68222 51 A 0
Pop1 ID68407 65 C 16 65
However, in lines 3 and 5, there are only 5 fields. In these cases, the 0 in field 5 is followed by a space character ('0 ').
I would like to find all instances of a space character at the end of a line (i.e. \s$ ) and replace it with space NA (i.e. '\sNA') but I am having real trouble doing so. For example, I have tried sed:
sed s/\\s$/\\sNA/g
but it's not working. Can someone help me out?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是
awk
中的几个等效解决方案:以下
Here's a couple of equivalent solutions in
awk
:and
\s
不能在替换字符串中使用,因为它是一个类。$
可能由 shell 解释。尝试:
\s
can't be used in the replacement string since it is a class.$
is probably being interpreted by the shell.Try:
使用实数空格代替 \s,并使用单引号 (
'
) 以避免 shell 执行变量替换:Put a real space instead of \s, and use single quote (
'
) to avoid the shell to perform variable substitution:您可以在纯 bash shell 中执行此操作,避免启动 sed 或 awk 进程:
You can do that in pure bash shell, avoiding to start a sed or awk process: