Find the answer to your Linux question:
Results 1 to 2 of 2
Hi all I am trying to write a bash script that will recognize a sequence of numbers and will replace them according an if statement. Could you please let me ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Apr 2012
    Posts
    57

    Assign rexeg result into var


    Hi all

    I am trying to write a bash script that will recognize a sequence of numbers and will replace them according an if statement.

    Could you please let me know how to assign that number that is recognized according to a regex into a variable? For instance, if my txt file looks like:

    Code:
    Text text text 15 text text text
    Text text text text text 7
    ….
    I want to replace all the numbers that are >=16.

    My code is :

    Code:
    while read line           
    do           
        number=$(echo $line | sed ‘s/[0-9][0-9]/g’)
    
    if [ $number >=16 ]
      then
        number=$( sed ‘s/([0-9])([0-9])/\2\1/g’)
    fi
             echo $number
    done <file.txt

    I would appreciate your help.

    Thanks

  2. #2
    Linux Engineer
    Join Date
    Dec 2013
    Posts
    1,305
    You might find it works better if you use bashes own regex matching.

    Code:
    while read line
    do
        if [[ $line =~ ^[0-9]+$ ]]; then
             if [[ $line -ge 16 ]]; then
                    echo $line
             fi
        fi
    done
    *forgot to add - you can split the line with for:
    Code:
    while read line
       for each in $line
       do
           echo $each
        done
    done

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •