I am having difficulty using sed or grep to extract a piece of text from a string.

An example string I am using is:

|a Milton, John, |d 1608-1674.

I am able to extract 'John' using sed, and some advice on the forums:

sed 's/[^,]*,\([^,]*\),.*/\1/'

But I am struggling with 'Milton'.

  • Do all the input lines start with |a , or are there other possible contents?
    – JigglyNaga
    Dec 8, 2017 at 17:09
  • "a|" is a constant, as is "d|". Obviously the name and dates vary! Dec 8, 2017 at 17:18

1 Answer 1


Assuming there's the |a at the start of the line, let's change that pattern a bit:

$ echo '|a Milton, John, |d 1608-1674.' | sed -E 's/^\|a ([^,]*), *([^,]*),.*/\1/'

sed -E uses extended regexes, so we can group with (...) without backslashes. Then we match the leading |a and the space, pick everything up to the next comma to a group ([^,]*),, ignore spaces with ␣*, and pick another group the same way as the first. The ,.* eats the rest of the line, and we can replace all of it with the first group \1 (here Milton), or the second group \2 (John).

Of course, if the |a is there to tell us what this particular field contains, and the fields might be in another order (like |d ... |a ...), then we'd need something different.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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