bash Grep 一行中的第一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36736084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grep the first number in a line
提问by Arnold Hotz
I have a file that has lines of numbers and a file:
我有一个包含数字行和文件的文件:
2 20 3 file1.txt
93 21 42 file2.txt
52 10 12 file3.txt
How do I use grep, awk, or some other command to just give me the first numbers of each line so that it will only display:
我如何使用 grep、awk 或其他一些命令来给我每行的第一个数字,以便它只显示:
2
93
52
Thanks.
谢谢。
回答by cdarke
So many ways to do this. Here are some (assuming the input file is gash.txt
):
有很多方法可以做到这一点。这里有一些(假设输入文件是gash.txt
):
awk '{print }' gash.txt
or using pure bash:
或使用纯 bash:
while read num rest
do
echo $num
done < gash.txt
or using "classic" sed
:
或使用“经典” sed
:
sed 's/[ \t]*\([0-9]\{1,\}\).*//' gash.txt
or using ERE with sed
:
或使用 ERE sed
:
sed -E 's/[ \t]*([0-9]+).*//' gash.txt
Using cut
is problematic because we don't know if the whitespace is spaces or tabs.
使用cut
是有问题的,因为我们不知道空格是空格还是制表符。
By the way, if you want to add the total number of lines:
顺便说一句,如果要添加总行数:
awk '{total+=} END{print "Total:",total}' gash.txt
回答by oliv
You can use awk
您可以使用 awk
awk '{print }' file
回答by blackSmith
You can use this:
你可以使用这个:
grep -oE '^\s*[0-9]+' filename
To handle the leading spaces, I'm currently out of options. You better accept the awk answer.
为了处理领先的空间,我目前别无选择。你最好接受 awk 答案。