Decreasing a number with sed

regular expressionsed

I extracted the metadata of a PDF in a .txt file using pdftk, and now I am trying to decrease the BookmarkPageNumber value for each bookmark by an integer. The .txt has these lines:

BookmarkBegin
BookmarkTitle: Preface
BookmarkLevel: 1
BookmarkPageNumber: 10
BookmarkBegin
BookmarkTitle: Author
... and so on

I am trying to do this using sed's substitute command, and here is what I have so far:

// $1 is the source .txt file; $2 is the decrement
// __ is a placeholder for the variable with the original value
cat $1 | sed "s/BookmarkPageNumber: [0-9]*/BookmarkPageNumber: `expr __ - $2`/" | cat > metadata.txt

How can I put the original value in a variable, and then replace the palceholder __ with it, within this same sed expression?

Best Answer

For that purpose is better use awk so as it support arithmetic operations

cat $1 | awk -v d=$2 '/BookmarkPageNumber:/{$2-=d}1'
Related Question