Vote count:
0
I have multiple files of the form
version 'aaa'
other 'bbb'
another 'ccc'
version 'ddd'
onemore 'eee'
Some have one version, others have multiple; same with the other keys, but the values never repeat. I’m using, as part of a bigger bash function, a perl one-liner to modify values
modify_value() {
key_to_modify="$1"
new_value="$2"
perl -i'' -pe "s|^(\s*)${key_to_modify} .*|\1${key_to_modify} ${new_value}|" "${file}"
}
This works great to an extent. I can do
modify_value "onemore" "fff"
And it will be correctly replaced in the text file. However, where it breaks down is where I have multiple keys with the same name (such as the aforementioned version), as this change will be made in all of them. In my particular case, I want the modification to be make always in the last case.
Since values are never repeated, so far what I have is
modify_value() {
key_to_modify="$1"
new_value="$2"
last_key=$(cat "${file}" | grep "^\s*${key_to_modify}" | tail -1 | perl -pe 's/^\s*//')
perl -i'' -pe "s|^(\s*)"${last_key}"|\1${key_to_modify} ${new_value}|" "${file}"
}
This works, but is a bit inelegant. Would it be possible to leverage the perl one-liner to act only on the latest occurrence of the match, instead?
asked 21 secs ago
Substitution only on last matching line (perl one-liner)
Aucun commentaire:
Enregistrer un commentaire