2

I have a file that contains these lines:

war {
    baseName = 'myApp'
    version = '1.0.2'
}

And a variable like:

variable=b123

I want to edit the file appending $variable value to the version number so result will be:

war {
    baseName = 'myApp'
    version = '1.0.2_b123'
}

How achieve this goal with a bash script?

1
  • bash isn't a text editor Commented Apr 20, 2017 at 18:26

2 Answers 2

6

Would a simple sed do?

$ var=_b123
$ sed -Ee "/version/s/'(.*)'/'\1$var'/" file 
war {
    baseName = 'myApp'
    version = '1.0.2_b123'
}

(/version/ checks if the line contains that string, if it does we substitute a string inside single quotes with the same string ((...) captures, \1 restores) plus the text in the variable. The quoting is not an issue here since everything we need is safe within double-quotes.)

0

If you like vim, this works:

vim +/version +"norm 2f'i_b123" +x file

This opens the file and executes three commands:

  • go to first line that contains "version"

  • enter normal mode, go to the second ', go to insert mode, insert _b123

  • write and quit

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.