I have a small bash script as follows :
cat foo.txt | grep "balt" > bar_file
As a side note: There is no need to use
cat and pipe its output to
grep since you can pass the filename directly to
grep which reduces a single process execution.
As for your question you can
-o option of
grep to get matching words only having
balt in them along with
\b boundary checking like this:
$ cat foo.txt abcd baltabcd xyz xdef abbaltcd xyz balt $ grep -o '\b\w*balt\w*\b' foo.txt baltabcd abbaltcd balt $ grep -o '\b\w*balt\w*\b' foo.txt > bar_file $ cat bar_file baltabcd abbaltcd balt $
As you can see grep matches 0 or more word characters present before or after
balt and puts that into another file.
Example words were: