-3

I want to find text inside a string Pattern from a data file and extract them in a text list using shell or AppleScript.

An example inside XML:

node file="source_files/ (var1) .mp3"

Another example inside HMTL:

src="http:// (example.com) /dir/ (var2) .txt"

Desired output:

1.1 source_files/example1.mp3
1.2 source_files/blah.blah

2.1 http://example.com/dir/example2.txt
2.2 http://example.com/dir/blah.blah

My question is this, how I am going to search, find and extract the series of all strings inside a text file that have the specific pattern of characters before, after or both?

  • You should give a more general description of the kind of strings you want to extract along and you should also give the desired output for your example input. – igal Dec 2 '17 at 16:05
  • Use an XML/HTML parser to parse XML/HTML – glenn jackman Dec 2 '17 at 22:00
  • So you just want to extract the hostname and file basename from each URL? – igal Dec 2 '17 at 23:48
2

How about using the following grep command:

grep -Po '(?<==")[^"]+(?=")'

This will extract double-quoted strings that appear after equal signs. Here it is in action:

user@host:~$ echo 'node file="source_files/example1.mp3"' \
| grep -Po '(?<==")[^"]+(?=")'

source_files/example1.mp3

user@host:~$ echo 'src="http://example2.com/dir/example2.txt"' \
| grep -Po '(?<==")[^"]+(?=")'

http://example2.com/dir/example2.txt
1
grep -F 'node file="source_files/example1.mp3"'

grep -F 'src="http://example2.com/dir/example2.txt"'

Not the answer you're looking for? Browse other questions tagged or ask your own question.