Search This Blog

Use GNU grep to count the length of substring between two words

Note: the command below requires GNU grep, it is available on Linux by default. On Mac OS, you need to install it manually using
brew install grep
and command is called ggrep instead of grep.


Get the substring between two words

echo "<person><name>abc</name></person>" | grep -o -P '(?<=<name>).*(?=</name>)'

Output should be:
abc



Count the length of substring

echo "<person><name>abc</name></person>" | grep -o -P '(?<=<name>).*(?=</name>)' | wc -c

Output should be:
3

Count substring lengths for each line

cat multi-lines.txt | while read line; do echo $line | grep -o -P '(?<=<name>).*(?=</name>)' | wc -c; done




see also

No comments:

Post a Comment