Loop through lines in file to find specified substring
I need to loop through a text file, line by line looking for a specified substring. If the substring is found in a line then echo that line and line number.
Can anyone help with this? |
I'll give you 2 methods:
Code:
grep -n string_to_search filename Code:
awk '/string_to_search/{print NR" "$0}' filename |
You can try this
Code:
nl <filename> | grep <substring> |
And here's another one:
Code:
cat -n filename | grep string_to_search |
AND---you can also do this with sed!!!
Is this homework by any chance? |
To pixellany: you often talk about homework, but I don't understand what is the problem. Sorry for post a message not related to the thread, but I am curious about this issue. Thank you.
|
Quote:
|
Got it. I agree. Thank you.
|
Quote:
I usually just respond unless the OP seems unable or unwilling to do anything on their own. Note that the rules don't prohibit asking or answering homework questions. They just say that their can be no expectation of help. |
I agree with you and with this rule. In the research world, where I'm working, I am expected to answer to all the questions from people who never wanted to waste a minute by figure out a solution by himself! It is part of my job and it is very frustrating, indeed. Anyway thank you for your answer. I have got the point, now.
|
My :twocents:
Quote:
Processing in Unix/Linux is often handled as a flow of textual data, passing though a number of specialized filters. The data goes from one utility to another through pipes until you get the result that you want. This works so well in Linux, even for audio or video, because of the "Everything is a File" principle. So you'd be better served thinking about the processing of a stream of characters, instead of ad hoc procedures. While a tool like sed does read in a file line by line, this detail is handled (hidden) in sed itself. |
Quote:
I thought the paradigm was: "Everything is a file." |
Hi.
Quote:
|
grep not reading input from loop
With the following code taking input from a file using a loop and the cat command, the grep command does not appear to be searching through the input. When executing the script it brings up a blank line waiting for input.
What am I doing wrong? #!/bin/bash # Find each line in a file that contains a # specified substring name=${0##*/} file=${1-'pwd'} if [ ! -f $file ]; then echo "'$file' is not a file" echo "Usage: $name [file]" exit 1 fi # Check if file has information. if [ ! -s $file ]; then echo "'$file' contains no information" exit 2 fi for line in `cat -n $file`; do grep 'one' done |
Quote:
However, a file in *nix is a stream of characters, whereas in other OS's there is Meta data externally associated with files. You can even set up a sparse drive with an echo command. Code:
To create a sparse device, start by creating a dm-zero device that's the |
All times are GMT -5. The time now is 11:16 AM. |