Home > Blockchain >  bash command to check if line has certain pattern
bash command to check if line has certain pattern

Time:01-08

I have a file in which I have to check a line that begins with a certain pattern. for example - id: 34. I wrote bash script but it does not seem to detect the line

#!/bin/bash

id=34

# Read the file line by line
while read line; do
  # Check if the line starts with pattern
  if [[ $line =~ ^[[:space:]]-[[:space:]]id:[[:space:]]$id ]]; then
    in_section=true
    echo "$line"
  fi

done < file.txt
 

sample file

$cat file.txt 
apiVersion: v1
data:
  topologydata: |
    config:
      topology:
        spspan:
        - id: 1
          name: hyudcda1-
          siteids:
          - 34
        spssite:
        - id: 34
          location: PCW
          matesite: tesan

CodePudding user response:

You was close, but better use grep:

grep -E "^[[:space:]] -[[:space:]] id:[[:space:]] $id" file

And you should give a try to a YAML parser: yq

CodePudding user response:

Your regular expression matches exactly one single space before the - character while read removes the leading and trailing spaces, so your $line variable value has zero leading spaces. Try:

^[[:space:]]*-[[:space:]]id:[[:space:]]$id

It will match with zero or any number of leading spaces. If you can also have zero or more than one space between - and id and between id and the integer, try:

^[[:space:]]*-[[:space:]]*id:[[:space:]]*$id

And if you want read to keep the leading spaces try:

while IFS= read line; do

Finally if, instead of zero or more, you want to match one or more spaces replace * by .

  •  Tags:  
  • bash
  • Related