Show surrounding lines in a text file given a string |
submit Problem Solving Skills, Human vs AI
Published Feb 11 '25 |
Tutorial #chatgpt #deepseek #genai #promptengineering
Today (2/11/2025) I ran into a problem that can be solved by Linux shell commands, but I don't know the exact commands needed to solve it, so I tried Google search engine which is my traditional approach to this kind of problem. I also tried AI chatbots including #ChatGPT and #DeepSeek and was impressed with their performance. Overall, lessons learned are:
Given a large text file and a string, find line in the file that matches the string, and also show surrounding lines.
To solve this problem, here are my steps using search engine:
find line number of a string in file linux
grep -n "your_string"
command in search resultshow certain lines of a file linux
$ grep -n "ABCD1234" ABC.txt
output: 1097994474:ABCD1234
$ head -1097994476 ABC.txt | tail -5
output: desired output
As part of #PromptEngineering effort, I constructed the prompt by rephrasing the problem statement more clearly as following and used it in both ChatGPT and DeepSeek, I also tried the same prompt in Google.
Please give me shell commands to complete this task on Linux: given a text file, ABC.txt, with multiple lines that contains a string "ABCD1234" only once in the file, show the line in the file that contains the string "ABCD1234" as well as 2 lines before it and 2 lines after it.
Here are how they performed.
Output from DeepSeek R1
You can use the grep
command with the -B
(before) and -A
(after) options to achieve this. Here's the command:
bash
grep -B 2 -A 2 "ABCD1234" ABC.txt
grep
: The command used to search for text within files.-B 2
: Shows 2 lines before the matching line.-A 2
: Shows 2 lines after the matching line."ABCD1234"
: The string you're searching for.ABC.txt
: The file in which to search.This command will output the line containing "ABCD1234" along with 2 lines before and 2 lines after it.
Output from ChatGPT
You can use the grep
command with the -C
(or --context
) option to show the matching line along with surrounding lines. Here’s the command:
sh
grep -C 2 "ABCD1234" ABC.txt
grep
searches for the string "ABCD1234"
in the file ABC.txt
.-C 2
(or --context=2
) displays 2 lines before and 2 lines after the matching line.If you want more control, you can also use awk
:
sh
awk '/ABCD1234/ {for(i=-2;i<=2;i++) if (NR+i in lines) print lines[NR+i]} {lines[NR]=$0}' ABC.txt
This method allows flexibility in adjusting the number of lines dynamically.
Search results did not show correct answer.
Terms of Use: You are in agreement with our Terms of Services and Privacy Policy. If you have any question or concern to any information published on SaveNowClub, please feel free to write to us at savenowclub@gmail.com