Extract a certain part of a string separated with "/"

Viewed 74

I have a list of file names

fastq/SRR17405580 
fastq/SRR17405578 
fastq/SRR17405579

I want to change their name to look like

SRR17405580 
SRR17405578 
SRR17405579
4 Answers

You could use basename() to remove all of the path up to and including the last path separator.

x <- c("fastq/SRR17405580", "fastq/SRR17405578", "fastq/SRR17405579")

basename(x)

# [1] "SRR17405580" "SRR17405578" "SRR17405579"

You could also use regex:

sub('.+/(.+)', '\\1', x)

# [1] "SRR17405580" "SRR17405578" "SRR17405579"

Another option is to use word from stringr package:

library(stringr)
word(x, 2, sep="/")

[1] "SRR17405580" "SRR17405578" "SRR17405579"

Another option using str_split from stringr like this:

library(stringr)
str_split(x, '/', simplify = TRUE)[,2]
#> [1] "SRR17405580" "SRR17405578" "SRR17405579"

Created on 2022-08-27 with reprex v2.0.2

Using trimws from base R

trimws(x, whitespace = ".*/")
[1] "SRR17405580" "SRR17405578" "SRR17405579"
Related