[英]Check if line starts with digit then put those lines in a separate file using Bash
I would like to check in bash if line starts with digit then put those lines in a separate file. 我想检查bash如果行以数字开头,然后将这些行放在单独的文件中。 I tried
^[[0-9]]
but it doesn't work. 我尝试了
^[[0-9]]
但是它不起作用。
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
The correct operator to use regex in Bash script is =~
. 在Bash脚本中使用正则表达式的正确运算符是
=~
。 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. 但是您不需要该工作的Bash循环。 You can do it with a sed one-liner:
您可以使用单线sed做到这一点:
sed '/^[0-9].*\.tests\./!d' "${myTestsFile}" > myFailedFile
Explanations (from right to left): 说明 (从右到左):
!d
: do not delete !d
:不删除 /^[0-9].*\\.tests\\./
: all lines that start with one or more digits and that contain .tests.
/^[0-9].*\\.tests\\./
:所有以一位或多位数字开头并且包含.tests.
string Without using regex you can use glob
as this: 无需使用正则表达式,您可以按以下方式使用
glob
:
[[ $line = [0-9]* ]] && [[ $line = *".tests."* ]]
[0-9]*
matches a string start start with digits [0-9]*
匹配以数字开头的字符串 *".tests."*
matches a string that contains .tests.
*".tests."*
与包含.tests.
的字符串匹配.tests.
you can use 您可以使用
if [[ ${line} =~ ^[0-9] && ${line} =~ ".tests." ]] ; then
or 要么
if [[ ${line} == [0-9]* && ${line} == *".tests."* ]] ; then
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.