8

If I have a file that looks like this:

example.png example.jpg example2.jpg example2.png example.swf
example2.swf example3.jpg example4.jpg example3.png example3.swf 

and I want to extract the words containing swf for example, the output would look something like this

example.swf 
example2.swf
example3.swf

I tried grep -o "swf[^[:space:]]*", which just prints a bunch of swf, and then I tried grep -o '[^ ]*a\.swf[^ ]*', which output very few lines containing "swf". Does anyone know what to do?

2
  • 3
    You're close I think - but don't you want grep -o '[^[:space:]]*swf' i.e. zero or more non-space characters before the swf substring? Feb 7, 2016 at 0:45
  • @steeldriver Why didn't you write that as an answer? You'd have received my upvote.
    – Sparhawk
    Feb 7, 2016 at 4:06

3 Answers 3

10

With GNU grep:

grep -o '\b\w*\.swf\b' file

Output:

example.swf
example2.swf
example3.swf

\b: a zero-width word boundary

\w: word character

\.: match one dot


See: The Stack Overflow Regular Expressions FAQ

5

You can do:

grep -o '[^ ]*\.swf' file.txt
  • [^ ]* matches zero or more non-space characters

  • \.swf matches literal .swf

Example:

% grep -o '[^ ]*\.swf' file.txt
example.swf
example2.swf
example3.swf
4

First step

Replace spaces with line ends using sed

Second step

Filter the output using grep

Example

sed -e s/\ /\\n/g file | grep .swf

1
  • 1
    simple and easy. good approach.
    – Ace
    Feb 7, 2016 at 1:01

You must log in to answer this question.

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