bash multiple if statement inside loop is not working

Muhammad Rashid :

I am new to bash scripting, I have a file and i want to check each line but it is not working.

My bach script code

declare -a arr

for (( i=0; i<${len}; i++ ))
do
    if [[ ${arr[$i]} =~ ^[0-9]+$ ]]
    then
      echo ${arr[$i]}" numbr"
    
    else
        echo "No match"
     fi
done

Why only last line is match ? is there any space or line break issue ? suggest me some solution

glenn jackman :

Your file is saved in "DOS" format, with \r\n line endings.

To convert to "unix" format:

dos2unix file.txt
# or, if that's not installed
sed -i 's/\r$//' file.txt

tangentially, I find the POSIX character class can describe what you want to match:

[[ ${arr[$i]} =~ ^[[:digit:]]+$ ]] && echo "${arr[i]} numbr"
[[ ${arr[$i]} =~ ^[[:alpha:]]+$ ]] && echo "${arr[i]} ltr only"
[[ ${arr[$i]} =~ ^[[:alnum:]]+$ ]] && echo "${arr[i]} both"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

break statement inside a for loop not working

Sed not working inside bash for loop

If statement not working inside foreach loop javascript

IF statement is not working properly inside the FOR loop of a Django project

Nested if/else statement inside for loop not working as expected

return statement inside a promise in a loop is not working

While loop inside if else statement not working

IF statement inside a loop in linux terminal not working

If statement inside a for loop doesn't working in Javascript

Return statement not working inside for loop in an async function

multiple loop inside single for statement using cursor

Using multiple if statement, between conditions, inside a for loop

javascript multiple AND conditions in IF statement inside for loop javascript

"read" not working if called inside bash while loop

Excel VBA Multiple if statement in loop working incorrectly

Multiple negative expression in if statement is not working in bash script

Bash 'if' statement in 'for' loop in an 'if' statement

Why is the else statement not working inside a foreach loop in php?

'except' in try statement (inside while loop) isn't working

Google Apps Script - if else statement inside for loop not working

If statement inside a for loop prints all values as true if any are - bash

Bash case statement using awk commands in a for loop not working

Error while trying to take multiple inputs in a switch inside a loop statement

How to include multiple conditions in if statement inside a while loop?

if statement is not working inside setInterval

Variable not working inside If statement

Running a loop inside if statement

If statement inside While loop

Avoiding if statement inside a for loop?