Elb*_*Elb 42 unix awk replace r sed
我有一个包含一定数量行的文件.每一行看起来像这样:
TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1
Run Code Online (Sandbox Code Playgroud)
我想删除所有":"之前的字符,以便仅保留作为基因名称的PKMYT1.由于我不是正则表达式脚本编写的专家,任何人都可以帮助我使用Unix(sed或awk)或R?
Sac*_*amp 61
以下是在R中执行此操作的两种方法:
foo <- "TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1"
# Remove all before and up to ":":
gsub(".*:","",foo)
# Extract everything behind ":":
regmatches(foo,gregexpr("(?<=:).*",foo,perl=TRUE))
Run Code Online (Sandbox Code Playgroud)
And*_*rie 11
一个简单的正则表达式用于gsub():
x <- "TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1"
gsub(".*:", "", x)
"PKMYT1"
Run Code Online (Sandbox Code Playgroud)
请参阅?regex或?gsub获取更多帮助.
小智 10
使用包str_remove中的解决方案stringr:
str_remove("TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1", ".*:")
[1] "PKMYT1"
Run Code Online (Sandbox Code Playgroud)
在R中肯定有两种以上的方法.这是另一种方式.
unlist(lapply(strsplit(foo, ':', fixed = TRUE), '[', 2))
Run Code Online (Sandbox Code Playgroud)
如果字符串具有恒定的长度,我想substr这将比这个或正则表达式方法更快.
使用sed:
sed 's/.*://' < your_input_file > output_file
Run Code Online (Sandbox Code Playgroud)
这将替换任何后跟冒号的东西,因此它将删除所有内容,包括每行的最后一个冒号(因为*默认情况下是贪婪的).
根据Josh O'Brien的评论,如果您只想更换并包含第一个冒号,请执行以下操作:
sed "s/[^:]*://"
Run Code Online (Sandbox Code Playgroud)
这将匹配任何不是冒号,后跟一个冒号的东西,并替换为空.
请注意,对于这两种模式,它们将在每行的第一场比赛中停止.如果要对一行上的每个匹配进行替换,请在命令末尾添加' g'(全局)选项.
另请注意,在linux上(但不是在OSX上),您可以使用-i例如以下内容编辑文件:
sed -i 's/.*://' your_file
Run Code Online (Sandbox Code Playgroud)
小智 6
我从最佳响应 @Sacha Epskamp 中错过的一些非常简单的举动是使用 sub 函数,在这种情况下,获取“:”之前的所有内容(而不是删除它),所以它非常简单:
foo <- "TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1"
# 1st, as she did to remove all before and up to ":":
gsub(".*:","",foo)
# 2nd, to keep everything before and up to ":":
gsub(":.*","",foo)
Run Code Online (Sandbox Code Playgroud)
基本上是同样的事情,只需更改子参数内的“:”位置即可。希望它会有所帮助。