1

I have a bash script with multiple functions. The function are set out exactly as below:

func1()
{
command
}
func2()
{
command
}

My problem is thus: If I want to remove func76(). The sequence of numbered functions is broken. How do I change the numbered part of all the function names to put them back into sequence? For instance, what was previously func77() will now become func76() and so on until the end. Any ideas?

0
2

The renaming task can quite easily be done with awk:

awk -v"a=1" '/func[0-9]+()/{$0="func"a"()";a+=1}1'

This replaces every line matching func[0-9]+() with a function name with an incrementing number and prints every line.

Explanations

  • -v"a=1" – set a=1 before execution of the program begins - /pattern/{action} – for lines matching the regular expression pattern, perform action
  • /func[0-9]+()/ – matches every line containing “func” followed by one or more digits ([0-9]+) and “()”
  • $0="func"a"()" – set the currently processed line ($0) to “func” followed by the content of variable a and “()”
  • a+=1 – increase a by one
  • 1 – shortcut to print the current line – in fact it‘s another statement with expression and action, just that the expression is simply 1 (= true for every line) and the action is the default one, which is print. You can replace this with {print} if you like.

Example run

$ <functions.bash cat
func1()
{
command1
}
func3()
{
command3
}
$ <functions.bash awk -v"a=1" '/func[0-9]+()/{$0="func"a"()";a+=1}1'
func1()
{
command1
}
func2()
{
command3
}
0

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.