In: Computer Science
Hello, I am using BASH. I need to write a conditional statement using grep. I want the computer to echo true if it detects any numerical character in the first line of StrepList.txt. However, the computer tells me that "grep: [0-9]: No such file or directory"
if (head -n 1 StrepList.txt | grep -o [0-9] -eq TRUE);then
echo "Contains numbers"
else
echo "No numbers"
fi
You've made some syntactical mistakes.
There is a mistake in the if statement,i.e,
if (head -n 1 StrepList.txt | grep -o [0-9] -eq TRUE) , the inner command must be enclosed in brackets preceded by $ symbol.
$(head -n 1 StrepList.txt | grep -o [0-9]) means it represents the whole output.
Another mistake is that the command returns a numerical value not a boolean value. Therefore "-eq TRUE" is not a correct statement. And there is no need of "semi column(;)" at the end of the if statement.
And use '-c' in the grep command instead of '-o'.
And use these brackets [ ] for if conditions.
Therefore the corrected code would be:
if [ $(head -n 1 StrepList.txt | grep -c [0-9]) -eq 1
]
then
echo "Contains numbers"
else
echo "No numbers"
fi
expected output:
if first line of file contains any number then
if first line doesn't have any numbers then,