Count number of occurrences of a pattern on same line2019 Community Moderator ElectionWhy is printf better than echo?Count lines matching pattern and matching previous lineCount number of sessions and email as a bodyFind strings in file1, count occurrences in file2To count number of matches in a mega string quicklyCount number of occurrences of a parentheses regexCount pattern and matching lines simultaneouslyHow to use sed to replace a string using the line number on a remote machine using ssh?How to count occurrences of each word belonging to a file in all of `n` number of files passed as arguments?Returning only the contents before and after a line number with different matching wordsCount the number of occurrences of a substring in a string
Did I make a mistake by ccing email to boss to others?
Given this phrasing in the lease, when should I pay my rent?
If Captain Marvel (MCU) were to have a child with a human male, would the child be human or Kree?
Isometric embedding of a genus g surface
Why didn’t Eve recognize the little cockroach as a living organism?
Why is the Sun approximated as a black body at ~ 5800 K?
Deciphering cause of death?
What is the meaning of the following sentence?
Why is the principal energy of an electron lower for excited electrons in a higher energy state?
How were servants to the Kaiser of Imperial Germany treated and where may I find more information on them
Should I warn new/prospective PhD Student that supervisor is terrible?
Do I have to know the General Relativity theory to understand the concept of inertial frame?
I'm just a whisper. Who am I?
Echo with obfuscation
Why do Radio Buttons not fill the entire outer circle?
How to get directions in deep space?
How to reduce predictors the right way for a logistic regression model
How do I Interface a PS/2 Keyboard without Modern Techniques?
Sound waves in different octaves
How to leave product feedback on macOS?
Giving feedback to someone without sounding prejudiced
Is it feasible to let a newcomer play the "Gandalf"-like figure I created for my campaign?
Is there anyway, I can have two passwords for my wi-fi
Integral Notations in Quantum Mechanics
Count number of occurrences of a pattern on same line
2019 Community Moderator ElectionWhy is printf better than echo?Count lines matching pattern and matching previous lineCount number of sessions and email as a bodyFind strings in file1, count occurrences in file2To count number of matches in a mega string quicklyCount number of occurrences of a parentheses regexCount pattern and matching lines simultaneouslyHow to use sed to replace a string using the line number on a remote machine using ssh?How to count occurrences of each word belonging to a file in all of `n` number of files passed as arguments?Returning only the contents before and after a line number with different matching wordsCount the number of occurrences of a substring in a string
I need to solve this in a shell script. I am counting number of occurrence of the abc
string below and I want to get the answer as 3.
echo abcsdabcsdabc | grep -o abc
abc
abc
abc
Assuming we do not have the -o
option in grep
, how do we approach this then?
shell-script
add a comment |
I need to solve this in a shell script. I am counting number of occurrence of the abc
string below and I want to get the answer as 3.
echo abcsdabcsdabc | grep -o abc
abc
abc
abc
Assuming we do not have the -o
option in grep
, how do we approach this then?
shell-script
What shell are you using?bash
?
– Kusalananda
20 hours ago
If your input string is known to contain no newlines, you can just feed the output to wcecho abcsdabcsdabc | grep -o abc| wc -l
, to count the lines.
– zeppelin
20 hours ago
add a comment |
I need to solve this in a shell script. I am counting number of occurrence of the abc
string below and I want to get the answer as 3.
echo abcsdabcsdabc | grep -o abc
abc
abc
abc
Assuming we do not have the -o
option in grep
, how do we approach this then?
shell-script
I need to solve this in a shell script. I am counting number of occurrence of the abc
string below and I want to get the answer as 3.
echo abcsdabcsdabc | grep -o abc
abc
abc
abc
Assuming we do not have the -o
option in grep
, how do we approach this then?
shell-script
shell-script
edited 20 hours ago
Rui F Ribeiro
41.6k1483141
41.6k1483141
asked 20 hours ago
MachineMachine
244
244
What shell are you using?bash
?
– Kusalananda
20 hours ago
If your input string is known to contain no newlines, you can just feed the output to wcecho abcsdabcsdabc | grep -o abc| wc -l
, to count the lines.
– zeppelin
20 hours ago
add a comment |
What shell are you using?bash
?
– Kusalananda
20 hours ago
If your input string is known to contain no newlines, you can just feed the output to wcecho abcsdabcsdabc | grep -o abc| wc -l
, to count the lines.
– zeppelin
20 hours ago
What shell are you using?
bash
?– Kusalananda
20 hours ago
What shell are you using?
bash
?– Kusalananda
20 hours ago
If your input string is known to contain no newlines, you can just feed the output to wc
echo abcsdabcsdabc | grep -o abc| wc -l
, to count the lines.– zeppelin
20 hours ago
If your input string is known to contain no newlines, you can just feed the output to wc
echo abcsdabcsdabc | grep -o abc| wc -l
, to count the lines.– zeppelin
20 hours ago
add a comment |
2 Answers
2
active
oldest
votes
With awk
:
awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc
Note that the pattern (here abc
) is taken by awk
as an extended regular expression (as if using grep -E
/egrep
).
That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo
which can't output arbitrary data.
To use perl
regular expressions (similar to GNU grep -P
's):
perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc
(note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é
and .
as arguments, it would report 2 (bytes) instead of 1 (character)).
add a comment |
Treating the string as consisting of fields that are delimited by abc
:
$ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
3
The number of occurrences of the delimiter abc
is 1 minus the number of fields that it delimits.
$ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
3
This deletes the substring abc
from the line and counts the number of times this is done, then outputs that number. The n=0
is not needed if there is only one line of input.
The gsub()
function in awk
returns the number of substitutions made, so the above could be simplified into
$ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
3
In bash
, you can do the same thing as in that awk
program that uses sub()
:
string=abcsdabcsdabc
n=0
while [[ $string == *abc* ]]; do
n=$(( n+1 ))
string=$string/abc/ # remove first occurrence of "abc"
done
printf '%dn' "$n"
This uses a while
loop to remove the substring abc
from the value in $string
until no further occurrences of abc
is found in $string
, just as the second awk
program above does.
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
1
@Machine I've explained it further now. The loop is looping until noabc
is found in$string
.
– Kusalananda
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
1
@Machine This is abash
-specific variable substitution that replaces the first occurrenceabc
in$string
with nothing. The general form is$variable/pattern/word
which replaces the first bit that matchespattern
in$variable
withword
. Using$variable//pattern/word
replaces all matches. This is described in thebash
manual. It is a feature of the shell, not of Unix.
– Kusalananda
18 hours ago
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "106"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f507368%2fcount-number-of-occurrences-of-a-pattern-on-same-line%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
With awk
:
awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc
Note that the pattern (here abc
) is taken by awk
as an extended regular expression (as if using grep -E
/egrep
).
That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo
which can't output arbitrary data.
To use perl
regular expressions (similar to GNU grep -P
's):
perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc
(note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é
and .
as arguments, it would report 2 (bytes) instead of 1 (character)).
add a comment |
With awk
:
awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc
Note that the pattern (here abc
) is taken by awk
as an extended regular expression (as if using grep -E
/egrep
).
That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo
which can't output arbitrary data.
To use perl
regular expressions (similar to GNU grep -P
's):
perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc
(note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é
and .
as arguments, it would report 2 (bytes) instead of 1 (character)).
add a comment |
With awk
:
awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc
Note that the pattern (here abc
) is taken by awk
as an extended regular expression (as if using grep -E
/egrep
).
That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo
which can't output arbitrary data.
To use perl
regular expressions (similar to GNU grep -P
's):
perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc
(note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é
and .
as arguments, it would report 2 (bytes) instead of 1 (character)).
With awk
:
awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc
Note that the pattern (here abc
) is taken by awk
as an extended regular expression (as if using grep -E
/egrep
).
That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo
which can't output arbitrary data.
To use perl
regular expressions (similar to GNU grep -P
's):
perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc
(note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é
and .
as arguments, it would report 2 (bytes) instead of 1 (character)).
edited 19 hours ago
answered 20 hours ago
Stéphane ChazelasStéphane Chazelas
310k57586945
310k57586945
add a comment |
add a comment |
Treating the string as consisting of fields that are delimited by abc
:
$ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
3
The number of occurrences of the delimiter abc
is 1 minus the number of fields that it delimits.
$ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
3
This deletes the substring abc
from the line and counts the number of times this is done, then outputs that number. The n=0
is not needed if there is only one line of input.
The gsub()
function in awk
returns the number of substitutions made, so the above could be simplified into
$ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
3
In bash
, you can do the same thing as in that awk
program that uses sub()
:
string=abcsdabcsdabc
n=0
while [[ $string == *abc* ]]; do
n=$(( n+1 ))
string=$string/abc/ # remove first occurrence of "abc"
done
printf '%dn' "$n"
This uses a while
loop to remove the substring abc
from the value in $string
until no further occurrences of abc
is found in $string
, just as the second awk
program above does.
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
1
@Machine I've explained it further now. The loop is looping until noabc
is found in$string
.
– Kusalananda
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
1
@Machine This is abash
-specific variable substitution that replaces the first occurrenceabc
in$string
with nothing. The general form is$variable/pattern/word
which replaces the first bit that matchespattern
in$variable
withword
. Using$variable//pattern/word
replaces all matches. This is described in thebash
manual. It is a feature of the shell, not of Unix.
– Kusalananda
18 hours ago
add a comment |
Treating the string as consisting of fields that are delimited by abc
:
$ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
3
The number of occurrences of the delimiter abc
is 1 minus the number of fields that it delimits.
$ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
3
This deletes the substring abc
from the line and counts the number of times this is done, then outputs that number. The n=0
is not needed if there is only one line of input.
The gsub()
function in awk
returns the number of substitutions made, so the above could be simplified into
$ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
3
In bash
, you can do the same thing as in that awk
program that uses sub()
:
string=abcsdabcsdabc
n=0
while [[ $string == *abc* ]]; do
n=$(( n+1 ))
string=$string/abc/ # remove first occurrence of "abc"
done
printf '%dn' "$n"
This uses a while
loop to remove the substring abc
from the value in $string
until no further occurrences of abc
is found in $string
, just as the second awk
program above does.
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
1
@Machine I've explained it further now. The loop is looping until noabc
is found in$string
.
– Kusalananda
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
1
@Machine This is abash
-specific variable substitution that replaces the first occurrenceabc
in$string
with nothing. The general form is$variable/pattern/word
which replaces the first bit that matchespattern
in$variable
withword
. Using$variable//pattern/word
replaces all matches. This is described in thebash
manual. It is a feature of the shell, not of Unix.
– Kusalananda
18 hours ago
add a comment |
Treating the string as consisting of fields that are delimited by abc
:
$ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
3
The number of occurrences of the delimiter abc
is 1 minus the number of fields that it delimits.
$ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
3
This deletes the substring abc
from the line and counts the number of times this is done, then outputs that number. The n=0
is not needed if there is only one line of input.
The gsub()
function in awk
returns the number of substitutions made, so the above could be simplified into
$ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
3
In bash
, you can do the same thing as in that awk
program that uses sub()
:
string=abcsdabcsdabc
n=0
while [[ $string == *abc* ]]; do
n=$(( n+1 ))
string=$string/abc/ # remove first occurrence of "abc"
done
printf '%dn' "$n"
This uses a while
loop to remove the substring abc
from the value in $string
until no further occurrences of abc
is found in $string
, just as the second awk
program above does.
Treating the string as consisting of fields that are delimited by abc
:
$ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
3
The number of occurrences of the delimiter abc
is 1 minus the number of fields that it delimits.
$ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
3
This deletes the substring abc
from the line and counts the number of times this is done, then outputs that number. The n=0
is not needed if there is only one line of input.
The gsub()
function in awk
returns the number of substitutions made, so the above could be simplified into
$ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
3
In bash
, you can do the same thing as in that awk
program that uses sub()
:
string=abcsdabcsdabc
n=0
while [[ $string == *abc* ]]; do
n=$(( n+1 ))
string=$string/abc/ # remove first occurrence of "abc"
done
printf '%dn' "$n"
This uses a while
loop to remove the substring abc
from the value in $string
until no further occurrences of abc
is found in $string
, just as the second awk
program above does.
edited 19 hours ago
answered 20 hours ago
KusalanandaKusalananda
136k17257426
136k17257426
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
1
@Machine I've explained it further now. The loop is looping until noabc
is found in$string
.
– Kusalananda
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
1
@Machine This is abash
-specific variable substitution that replaces the first occurrenceabc
in$string
with nothing. The general form is$variable/pattern/word
which replaces the first bit that matchespattern
in$variable
withword
. Using$variable//pattern/word
replaces all matches. This is described in thebash
manual. It is a feature of the shell, not of Unix.
– Kusalananda
18 hours ago
add a comment |
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
1
@Machine I've explained it further now. The loop is looping until noabc
is found in$string
.
– Kusalananda
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
1
@Machine This is abash
-specific variable substitution that replaces the first occurrenceabc
in$string
with nothing. The general form is$variable/pattern/word
which replaces the first bit that matchespattern
in$variable
withword
. Using$variable//pattern/word
replaces all matches. This is described in thebash
manual. It is a feature of the shell, not of Unix.
– Kusalananda
18 hours ago
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise
– Machine
19 hours ago
1
1
@Machine I've explained it further now. The loop is looping until no
abc
is found in $string
.– Kusalananda
19 hours ago
@Machine I've explained it further now. The loop is looping until no
abc
is found in $string
.– Kusalananda
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here
– Machine
19 hours ago
1
1
@Machine This is a
bash
-specific variable substitution that replaces the first occurrence abc
in $string
with nothing. The general form is $variable/pattern/word
which replaces the first bit that matches pattern
in $variable
with word
. Using $variable//pattern/word
replaces all matches. This is described in the bash
manual. It is a feature of the shell, not of Unix.– Kusalananda
18 hours ago
@Machine This is a
bash
-specific variable substitution that replaces the first occurrence abc
in $string
with nothing. The general form is $variable/pattern/word
which replaces the first bit that matches pattern
in $variable
with word
. Using $variable//pattern/word
replaces all matches. This is described in the bash
manual. It is a feature of the shell, not of Unix.– Kusalananda
18 hours ago
add a comment |
Thanks for contributing an answer to Unix & Linux Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f507368%2fcount-number-of-occurrences-of-a-pattern-on-same-line%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What shell are you using?
bash
?– Kusalananda
20 hours ago
If your input string is known to contain no newlines, you can just feed the output to wc
echo abcsdabcsdabc | grep -o abc| wc -l
, to count the lines.– zeppelin
20 hours ago