Sakura
Sakura

Reputation: 729

grep string from file in R

When I use the command below to grep my target string px

x <- grep('px', readLines("file.txt"))

[]an$px  

[1] 2 12  # x returns 2 and 12th line

But when I want to grep the string as [1]$px

x <- grep('[1]$px', readLines("file.txt"))

x returns integer(0)

My question is, how can I get 2 and 12 as well rather than integer(0) if my targeted string is [1]$px?

Upvotes: 0

Views: 1670

Answers (1)

Dason
Dason

Reputation: 61913

Brackets carry special meaning in regular expressions. Add fixed=TRUE to your parameters in grep tells it to interpret the pattern as is. The other option is to escape the brackets but if you don't need the full power of regular expressions and just want to search for a specific string then using fixed=TRUE is the better option anyways.

x <- grep('[[1]]$px', readLines("file.txt"), fixed = TRUE)

Upvotes: 3

Related Questions