I would like to check in bash if line starts with digit then put those lines in a separate file. I tried ^[[0-9]]
but it doesn’t work.
Here is the code which I tried:
myFailedFile=/tmp/1.txt myTestsFile: 177711 TESTING ...yahoo.tests.calendar.resources.scheduler.1 854756 TESTING ...yahoo.tests.calendar.resources.scheduler.2 * 2102637 DONE ...yahoo.tests.mail.contacts.add.3 while read line do if ( [[ ${line} = "^[[0-9]]"* ]] && [[ ${line} = *".tests."* ]] ); then echo -e "${line}r" >> ${myFailedFile} fi done <"${myTestsFile}" Expected output of myFailedFile: 177711 TESTING ...yahoo.tests.calendar.resources.scheduler.1 854756 TESTING ...yahoo.tests.calendar.resources.scheduler.2
Advertisement
Answer
The correct operator to use regex in Bash script is =~
. Moreoever you don’t need to double [
in range of characters. Try this:
while read line do if ( [[ ${line} =~ ^[0-9] ]] && [[ ${line} = *".tests."* ]] ); then echo -e "${line}r" >> ${myFailedFile} fi done <"${myTestsFile}"
Edit:
But you don’t need a Bash loop for that job. You can do it with a sed one-liner:
sed '/^[0-9].*.tests./!d' "${myTestsFile}" > myFailedFile
Explanations(from right to left):
!d
: do not delete/^[0-9].*.tests./
: all lines that start with one or more digits and that contain.tests.
string