Documenting files with sed

All,
I am looking for a way to improve this small one liner.

one of the files has this kind of format

public func <<<T>(array: [T], offset: Int) -> [T] { return array.shiftedLeft(by: offset)  }
gsed -i '/public func/i /\/\/\public func \n/\/\==mark==public func' t

results in

///public func 
//==mark==public func
public func <<<T>(array: [T], offset: Int) -> [T] { return array.shiftedLeft(by: offset)  }

i'd like the code to quickly parse to grab all of the string until it the first left parenthesis.

///public func <<<T>(array: [T], offset: Int) 
//==mark==public func <<<T>(array: [T], offset: Int) 
public func <<<T>(array: [T], offset: Int) -> [T] { return array.shiftedLeft(by: offset)  }

Thanks!

Where would you locate the "first left parenthesis"?

1 Like

judging from your example outcome you perhaps mean right bracket yes:

///public func <<<T>(array: [T], offset: Int) 
//==mark==public func <<<T>(array: [T], offset: Int) 
public func <<<T>(array: [T], offset: Int) -> [T] { return array.shiftedLeft(by: offset)  }

Try this - i have made your one-liner a multi-liner, btw., because it is easier to keep track of. You can convert it into a - quite unreadable - one-liner again, if you insist in unintelligible code. :wink:

sed '/public func/ {
                    h
                    s/^[[:blank:]]*//\/\/\//
                    s/\([^)]*)\).*/\1/p
                    s/^\/\/\//\/\/==mark==/p
                    g
               }' /path/to/file

Here is a version with commentary:

sed '/public func/ {                          # for every line with "pub..." do:
               h                              # copy line to hold space
               s/^[[:blank:]]*//\/\/\//       # replace leading blanks (if any) with three slashes
               s/\([^)]*)\).*/\1/p            # remove everything after first ")" and print the result
               s/^\/\/\//\/\/==mark==/p       # replace leading "///" with "//==mark==" and print again
               g                              # copy hold space (original line) back to pattern space
     }'

Notice that " sed -i " is a GNU-speciality and is not recommended to use. Instead write to a temporary file and move this over the original (once you are satisfied). sed -i does the same, but behind your back and in case something goes wrong you have less options to troubleshoot that.

I hope this helps.

bakunin

1 Like

Right parenthesis seems better, thanks Bakunin. Try also

sed 's/public func[^)]*)/\/\/&\n\/\/==mark==&\n&/' file
//public func <<<T>(array: [T], offset: Int)
//==mark==public func <<<T>(array: [T], offset: Int)
public func <<<T>(array: [T], offset: Int) -> [T] { return array.shiftedLeft(by: offset)  }
1 Like

yes sorry, my mistake, right parenthesis.

With another separator we don't need to \/ each literal /
As classic multi-line ( \ plus newline instead of gsed-only \n )

sed 's#public func[^)]*)#///&\
//==mark==&\
&#' t
1 Like