简体   繁体   English

重击:正则表达式匹配字符的第一次出现

[英]Bash: Regex match betwen first occurrence of characters

Input: 输入:

p45-322-16.jpg

Desired output: 所需的输出:

p45

I'm trying to make a bash script with grep or awk or sed or something that could run on a bash shell. 我正在尝试使用grep或awk或sed或可以在bash shell上运行的东西制作bash脚本。

Currently I'm stuck with this: 目前,我对此感到困惑:

echo "p45-322-16.jpg" | sed 's/\(.*\)-.*/\1/'

Output: 输出:

p45-322

You need to limit what you will accept. 您需要限制您将接受的内容。 Right now, you are accepting too much by using . 现在,您使用接受了太多. , and the greedy-by-default nature of regexes is consuming too many characters. ,并且正则表达式的默认贪婪特性消耗了太多字符。

Try either limiting the accepted characters to digits only, or specifically excluding the dash: 尝试将接受的字符限制为仅数字,或专门排除破折号:

\([0-9]*\).*

\([^-]*\).*
echo "p45-322-16.jpg" | sed 's/\([^-]*\).*/\1/'

The .* part of your regex is greedy, so it reads as far as possible so that the regex still matches. 正则表达式的.*部分是贪婪的,因此它会尽可能地读取以便正则表达式仍然匹配。 This means it claims everything up to the last - . 这意味着它要求一切到最后-

Use [^-]* to match everything until a - . 使用[^-]*匹配的一切,直到-

You can use cut command: echo "p45-322-16.jpg" | cut -d"-" -f1 您可以使用cut命令: echo "p45-322-16.jpg" | cut -d"-" -f1 echo "p45-322-16.jpg" | cut -d"-" -f1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM