Mr Toni WP
Mr Toni WP

Reputation: 191

How to display a word from different lines?

I wanna be able to display every line that has the word from input read. Now Im able to display the index position of the input read word.

echo "Filename"
read file

echo "A word"
read word

echo $file | awk '{print index($0,"'"$word"'")}'

Upvotes: 1

Views: 96

Answers (2)

gboffi
gboffi

Reputation: 25023

If you want to print also the line number

read -p 'Filename? ' fname
read -p 'Word to search? ' word
awk /"$word"/'{print NR, $0}' "$fname"

If you don't want the line number

read -p 'Filename? ' fname
read -p 'Word to search? ' word
awk /"$word"/ "$fname"

BTW, what everyone told you is "use grep", but look at this

% time for i in {1..10000} ; do grep alias .bashrc > /dev/null ; done

real    0m22.665s
user    0m2.672s
sys     0m3.564s
% time for i in {1..10000} ; do mawk /alias/ .bashrc > /dev/null ; done

real    0m21.951s
user    0m3.412s
sys     0m3.636s

Of course gawk is slower, in this case 27.9 seconds.

Upvotes: 1

Michael Coleman
Michael Coleman

Reputation: 3398

as requested here is an example of how you could use grep.
The following command will use wget to fetch the content of this stackoverflow webpage, the -O - option tells wget to output the html into std out, which then gets piped into grep -n grep.
grep matches the number of instances the term "grep" appears in the html and then outputs with the corresponding line number where the match occurs - and highlights the match.

wget -O - http://stackoverflow.com/questions/27691506/how-to-display-a-word-from-different-lines | grep -n grep

e.g. When I run in my terminal (ignoring the wget related output) grep -n grepgives:

42: <span class="comment-copy">why dont you use <code>grep</code> ?</span>
468: <span class="comment-copy">@nu11p01n73R Can you give me any example, on how to use grep?</span>
495: <span class="comment-copy">As per your question <code>grep $word $file</code> will output lines in <code>$file</code> containing <code>$word</code></span>
521: <span class="comment-copy">If you want line numbers too, you can use <code>grep</code> like this: <code>grep -in $word $file</code></span>

Note stackoverflow syntax highlighting is different to what you get in terminal

Upvotes: 1

Related Questions