Reputation: 117
I am trying to create a script that dynamically finds line numbers in a .groovy config file and then utilizes the 'head/tail' command to insert multiple lines of code into the .groovy' config file. I cannot hardcode line numbers into the script because the vendor may alter the config and order of line numbers in the future. Anybody have suggestions for the best way to accomplish this?
EX.)
1: This is line one
2: This is line two
Problem: I need to insert:
test {
test{
authenticationProvider =/random/path
}
}
I cannot hard code the lie numbers in sed because they may change in the future. How can I dynamically make sed find the appropriate line number and insert multiple lines of code in the proper format?
Upvotes: -1
Views: 224
Reputation: 67467
this should do
$ line_num=2; seq 5 | sed "${line_num}r insert"
1
2
test {
test{
authenticationProvider =/random/path
}
}
3
4
5
to be inserted text is placed in the file named insert
. Since there is no sample input file, I generated sequence of 5 as the input source.
Upvotes: 2
Reputation: 12201
Assuming you can find the line number, you could do this fairly easy with a bash script:
file insert-lines.sh
:
#!/bin/bash
MYLINE=$1
FILE=$2
head -$MYLINE < $FILE
cat <<__END__
test {
test{
authenticationProvider =/random/path
}
}
__END__
tail +$((MYLINE+1)) $FILE
Then you can run this:
chmod 755 insert-lines.sh
./insert-lines.sh 3 .groovy > .groovy.new
mv .groovy.new .groovy
and the script will insert the block between lines 3 and 4 of the .groovy file.
Note that I'm assuming a recent Linux distro which supports the tail +n
syntax, which outputs the end of the file starting at line n. You'll have to replace that part of the code if your version of tail
does not support it.
Upvotes: -1