[英]shell script of grep single line in bash script
I have a file with the following format: 我有一个具有以下格式的文件:
123 2 3 48 85.64 85.95
Park ParkName Location
12 2.2 3.2 48 5.4 8.9
Now I could like to write a shell script to extract lines from this file. 现在,我想编写一个Shell脚本以从该文件中提取行。 The first item from each line is a kind of flag.
每行的第一项是一种标记。 For different flags, I will make different process.
对于不同的标志,我将进行不同的处理。 See my code below:
请参阅下面的代码:
head= ` echo "$line" | grep -P "^\d+" `
if [ "$head" != "" ]; then
(do something...)
fi
head=` echo "$line" | grep -P "^[A-Z]+" `
if [ "$head" != "" ]; then
(do something...)
fi
The code works. 该代码有效。 But I dislike the complicated way of writing 2 "if".
但是我不喜欢写2“ if”的复杂方式。 I would like to have something simple like:
我想要简单的东西:
if [ "$head" != "" ]; then
(do something...)
elif [ "$head" != "" ]; then
(do something...)
fi
Any thoughts? 有什么想法吗?
How about pure bash solution? 纯bash解决方案如何? Bash has a built-in regexp functionality, that you trigger with
~
character. Bash具有内置的正则表达式功能,您可以使用
~
字符来触发。 Be aware though that processing huge files with bash read line will not yield in optimal performance.. 请注意,尽管使用bash读取行处理巨大的文件不会产生最佳性能。
#!/bin/bash
file=$1
while read line
do
echo "read [$line]"
if [[ $line =~ ^[0-9] ]]; then
echo ' Processing numeric line'
elif [[ $line =~ ^[A-Za-z] ]]; then
echo ' Processing a text line'
fi
done < $file
How about this. 这个怎么样。 I guess it would fulfill your requirement
我想它将满足您的要求
file 文件
123 2 3 48 85.64 85.95
123 2 3 48 85.64 85.95
Park ParkName Location
公园ParkName地点
12 2.2 3.2 48 5.4 8.9
12 2.2 3.2 48 5.4 8.9
script.sh script.sh
while read line
do
echo $line | grep -qP "^\d+" && echo "Line starts with Numbers"
echo $line | grep -qP "^[a-zA-Z]+" && echo "Line Starts with String"
done < file
Output:- 输出: -
bash script.sh
Line starts with Numbers
行以数字开头
Line Starts with String
行以字符串开头
Line starts with Numbers
行以数字开头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.