Home > OS >  How do I match a command line argument in an if condition?
How do I match a command line argument in an if condition?

Time:10-24

I want to read from a yml file line by line and want to check if a command line argument is in the line, if it is I want to put the entire line in a different file.

Below is the simplified version of the code I am working with.

while IFS= read -r line; do
    if [[ "$line" =~ ".*$1:" ]]; then
        echo "$line" >> file_copy.yml
    fi
done < file.yml

I have tried "$line" == *".*\$1:"* but it didn't work.

Edit:

As soon as I pass a command line argument it says there is a syntax error.

CodePudding user response:

u can not quote regex expression; for example:

if [[ "abc" =~ ".*a" ]]; then echo "true"; fi    # --> This error

if [[ "abc" =~ .*a ]]; then echo "true"; fi      # --> This ok

doc

this may work

while IFS= read -r line; do
if [[ "$line" =~ .*$1: ]]; then
    echo "$line" >> file_copy.yml
fi
done < file.yml

CodePudding user response:

If you just want to see whether $1 is a literal substring of $line,

 [[ $line == *$1* ]]

would test it; no regex matching needed.

  •  Tags:  
  • bash
  • Related