Home > Enterprise >  Regex: Check that file contains a line three times
Regex: Check that file contains a line three times

Time:01-06

How can I check with a regex that a file contains the same line "this is 123" (with indentation) exact three times?

File:

<dev>
  <source file='/path/to/file'/>
  <string>this is 123</string>
</dev>

<dev>
  <source dev='this dev'/>
  <string>this is 123</string>
</dev>

<dev>
  <source dev='another dev'/>
  <string>this is 123</string>
</dev>

CodePudding user response:

you could use awk to count the lines

awk '/  <string>this is 123</string>/ { count   } END { print count }' file.txt

the string to use is enclosed in /s. After every line that awk encounters it increments a count and when it reaches the END it prints the count

use that count to compare in a conditional

c=$(awk '/  <string>this is 123</string>/ { count   } END { print count }' file.txt)
if [[ c -eq 3 ]]; then
    # do stuff
fi
  •  Tags:  
  • Related