Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match two consecutive lines using Regex and Bash features only

Tags:

regex

bash

What Regular Expression(s) can you use to match two consecutive lines? The aim is not to use any packages like awk or sed but only use pure RegExp inside a shell script.

Example, I would like to ensure the word "hello" is immediately followed by "world" in the next line.

Acceptance criteria:

  • "hello" is not to have any spaces before it
  • "world" must have at least 1 or more space before it.
#/bin/bash

file=./myfile.txt

regex='^hello'

[[ `cat $file` =~ $regexp ]] && echo "yes" || echo "no"

myfile.txt

abc is def
hello
 world
cde is efg

like image 933
meteorBuzz Avatar asked Jun 25 '26 13:06

meteorBuzz


1 Answers

Here is pure bash way:

file='./myfile.txt'
[[ $(<$file) =~ hello$'\n'[[:blank:]]*world ]] && echo "yes" || echo "no"

yes

Here $'\n' matches a new line and [[:blank:]]* matches 0+ tabs or spaces.

If you want to be more precise then use:

[[ $(<file) =~ (^|$'\n')hello$'\n'[[:blank:]]*world($'\n'|$) ]] && echo "yes" || echo "no"

However grep or awk are much better tools for this job.

like image 103
anubhava Avatar answered Jun 28 '26 04:06

anubhava