Hi, I am a beginner in R. I want to grep "x" from file1 and pipe it with line count command to know how many lines in file1 contain "X". What is the command for it?
Hi, I am a beginner in R. I want to grep "x" from file1 and pipe it with line count command to know how many lines in file1 contain "X". What is the command for it?
Let's say we have below file:
file1.txt
texst1 test1
test2 test1
test3 test1
test4 xtexst1
test5x test1
We can read the file, and use grepl
to search for "x". grepl
returns TRUE for matches, then we can sum
to get the count.
myFile <- readLines("file1.txt")
sum(grepl(pattern = "x", x = myFile))
# [1] 3
Shell / BASH:
cat test
echo on
hello world
hello world
alo mundo
alo mundo
hola mundo
hola mundo
echo off
Then, load R:
R
system("grep -e 'hello' test | wc -l")
2
system("grep -e 'echo' test | wc -l")
2
system("grep -e 'echo' test")
echo on
echo off
system("grep -e 'mundo' test | wc -l")
4
system("grep -e 'mundo' test")
alo mundo
alo mundo
hola mundo
hola mundo
system()
allows you to invoke operating system commands.
You can also read the file into R but it would help if it were TSV or CSV, an there run the grep()
R command.
Kevin
Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Why do you need to do this in R, if there are many (bash + grep, perl, python; to name just three) better tools for the task?
I understand that OP wants grep and wc functions in R for "x". IMO, this is kind of looking for duplicates i.e count the lines where X is present more than once. This function might do that: (Assumption is that X is present once in a line and X is not part of a string).