Substring Problem with sed . . .

Greetings.

I'm looking to isolate the first occurrence of an arbitrary substring which may be present at any particular line in a given file. The enclosing end markers for the target in our thought problem are string" and " . The complete string and surrounding text could look something like this,

a bunch of lines
"blah' blah string"1.2.3.4.5.6" "sputter" "thump!"
another line
etc

...with 1.2.3.4.5.6 being our target substring.

To scrape this problem off my plate, I've tried numerous approaches; including things like

sed -i '/string\"/,/\"/!d' ./testfile

...with much hair loss and screen damage :frowning:

Any tips for "happy sedding" through this wicket?

Thanks!

LinQ -

sed -n -e 's/^.*string"\([^"]*\)".*$/\1/p' file

will print only the target strings, skipping those lines that don't match.

  • DL
1 Like

something like this with awk:

awk -v qq='"' '{if (match($0, qq "[0-9.][0-9.]*" qq)) print substr($0,RSTART+1, RLENGTH-2)}' myFile

or with sed:

sed -n 's/.*"\([0-9.][0-9.]*\)".*/\1/p' myFile
1 Like

Thanks for the input.

In the end, I settled on a combination of the foregoing examples; and wound up with a pretty good line:

sed -n 's/^.*string="\([^"]*\).*$/\1/p' ./testfile

Cheers! :wink: