74i8Un3 74i8Un3 - 10 months ago 56
Bash Question

Cut words from files based on grep

I have a small bash script as follows :

cat foo.txt | grep "balt" > bar_file

Ideally what I would like to happen is that every word that contains
, I would like removed from the
file. Can I get direction on how to basically move words from one file from another based on whats grepped.

Answer Source

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
$ grep -o '\b\w*balt\w*\b' foo.txt 
$ grep -o '\b\w*balt\w*\b' foo.txt > bar_file
$ cat bar_file 

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: baltabcd, abbaltcd and balt