-1

I have a string like: func showFetchNextSliceFailed(result: UserResult<[Product]>) {

From this, I would like to 1). extract just showFetchNextSliceFailed 2). Insert it right above the given line, as #Mark showFetchNextSliceFailed.

  func showProductsList(result: UserResult<[Product]>) {

  }

  func showFetchNextSliceFailed(result: UserResult<[Product]>) {

  }

Expected output:

  #Mark showProductsList
  func showProductsList(result: UserResult<[Product]>) {

  }

  #Mark showFetchNextSliceFailed
  func showFetchNextSliceFailed(result: UserResult<[Product]>) {

  }

I tried with grep and sed, but still can't figure out correctly how to extract and replace strings.

closed as off-topic by Kusalananda, Jeff Schaller, vonbrand, X Tian, Anthony Geoghegan May 17 '18 at 16:58

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question has been posted on multiple sites. Cross-posting is strongly discouraged; see the help center and community FAQ for more information." – Kusalananda, Jeff Schaller, vonbrand, X Tian, Anthony Geoghegan

3

With sed

  • copy the matching pattern space to hold space
  • modify the pattern space
  • recover the original from hold space and append it

Ex.

$ sed '/func show/ {h; s/func \(show[^(]*\).*/#Mark \1/; G;}' file
  #Mark showProductsList
  func showProductsList(result: UserResult<[Product]>) {

  }

  #Mark showFetchNextSliceFailed
  func showFetchNextSliceFailed(result: UserResult<[Product]>) {

  }
0

If you have the following code file:

INPUT:

  $more code
  func showProductsList(result: UserResult<[Product]>) {

  }

  func showFetchNextSliceFailed(result: UserResult<[Product]>) {

  }

COMMAND:

perl -i.bak -pe "s/^^( *|\t*)func\s(\w+)func\s(\w+)/\1#Mark \2\n\1func \2/g" code

OUTPUT:

  #Mark showProductsList
  func showProductsList(result: UserResult<[Product]>) {

  }

  #Mark showFetchNextSliceFailed
  func showFetchNextSliceFailed(result: UserResult<[Product]>) {

  }

EXPLANATIONS:

  • -i.bak in-place mode for perl with backup of the input file
  • s/^( *|\t*)func\s(\w+)func\s(\w+)/\1#Mark \2\n\1func \2/g find and replace mode detailed at demo

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