如何在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 tellsgrepthe 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 1Flag: This makesgrepstop 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
相关产品推荐
相关产品推荐

