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 "balt"
, I would like removed from the foo.txt
file. Can I get direction on how to basically move words from one file from another based on whats grepped.
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: baltabcd
, abbaltcd
and balt