You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell脚本中使用grep匹配行尾的指定字符串?

Correct Approach to Match Trailing Numbers (First Line Only)

I see your issue—you want to match lines where your search number is the exact trailing number (not part of a larger number, like 11 when searching for 1) and only grab the first matching line. Here's how to adjust your script:

echo "Enter the content you are searching for:"
read foo

# Capture the first line that ends with a space + your number
if match=$(grep -m 1 " $foo\$" GUTINDEX.ALL); then
    echo "First matching line:"
    echo "$match"
else
    echo "No lines found ending with that number."
fi

Key Fixes Explained:

  • Regex " $foo\$":
    • The leading space ensures we're targeting the number at the end of the line (since your lines have a space before the trailing number).
    • The \$ is the end-of-line anchor—this tells grep the number must be the very last thing on the line. This prevents matches where your number is part of a larger trailing value (like 11 when searching for 1) or appears somewhere in the middle of the line.
  • -m 1 Flag: This makes grep stop searching immediately after finding the first match, which is exactly what you need instead of returning all matches.

Example Output:

If you input 1 when prompted:

  • You'll get only: Try and Trust, by Horatio Alger, Jr. 1
  • The second line (ending with 11) and third line (with "Part 1") won't be matched—perfect!

If you input 11, it will only return the second line, and inputting 23 will return the third line.


内容的提问来源于stack exchange,提问作者Safin Mahmud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:31:51