0

Let's say I have a list of words I want to keep.

list=['hi','name','first']

I want to be able to go through a text file, keep each and every word in my list, and output the new cleaned up content to a new file. For example:

have:

hi my name is Mike. Please write your name here first and then sign there.

want:

hi name name first

1 Answer 1

2

If you have the words in a separate file, one per line, you can use grep:

grep -oFf word-list.txt input-file
  • -o prints only matching strings
  • -F treats the patterns as fixed strings instead of regular expressions
  • -f file reads in patterns from a file.

With python:

#! /usr/bin/env python3

import sys
words=['hi','name','first']
for line in sys.stdin:
    print(' '.join(filter(lambda x: x in words, line.split())))
4
  • The grep version of the answer does not work: substrings match (for example first will match if firstname is in the file being searched). I am not overly versed in Python, but this seems to do it right, I would have offered a similar solution with awk.
    – asoundmove
    Mar 17, 2015 at 4:49
  • 1
    @asoundmove use -w, then.
    – muru
    Mar 17, 2015 at 4:50
  • Sure, I did forget that one.
    – asoundmove
    Mar 17, 2015 at 4:55
  • 1
    or shorter: print((" ").join([w for w in open("/file").read().split() if w in l])) (where l=['hi','name','first'] without importing sys) Mar 17, 2015 at 6:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .