简体   繁体   中英

Bash: Change “Title” of postscript file

I have a postscript file where I'd like to change the "Title" attribute before generating a pdf from it.

Following the beginning of the file:

%!PS-Adobe-3.0
%%BoundingBox: 0 0 595 842
%%HiResBoundingBox: 0 0 595 842
%%Title: GMT v5.1.1_r12693 [64-bit] Document from pscoast
%%Creator: GMT5
[…]

I now match the line %%Title: GMT v5.1.1_r12693 [64-bit] Document from pscoast with ^%%Title:\\s.* and like to replace everything after the colon with the content of a variable.

My non-working code so far:

sed "s/\(^%%Title:\)\s.*$/\1 $title/g" test_file.ps

My sed knowledge is very limited and my experimentation didn't yield anything useful so far - your help will be greatly appreciated.

All the best, Chris

EDIT: added my non-working code

One of the tricks for getting sed to work correctly is getting the shell quoting right. This creates a postscript file with the new title:

newtitle="Shiny New Title"
sed 's/^%%Title:.*/%%Title: '"$newtitle/" sample.ps >new.ps

This updates the postscript in place:

newtitle="Shiny New Title"
sed -i 's/^%%Title:.*/%%Title: '"$newtitle/" sample.ps

Many of the characters that one uses in sed expressions, like $ , ( , or * , are shell-active. To protect them from possible shell expansion, they should be in single-quotes. However, because one wants the shell to expand the $newtitle variable, it cannot be in single-quotes. Thus, if you look carefully, you will see that the above substitute expression is in two parts, one single-quoted and one double-quoted. Adding a space between them to make it clearer:

's/^%%Title:.*/%%Title: ' "$newtitle/" # Do not use this form.

Thus, the shell-active characters are protected by single-quotes and only the parts that we want the shell to mess with are in double-quotes

Maybe this is what you're looking for:

myvar="some content"
sed -e "s/^\(%%Title:\).*/\1 $myvar/" < inputfile

# output
...
%%Title: some content
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM