我需要更改许多pdf文件的标题。 Pdftk运作良好,我尝试创建一个bash脚本(pdftitle)以使其一次通过:
#!/bin/bash
newtitle=$2
pdftk "$1" data_dump output "$1".data.txt;
sed 's/^InfoKey:\sTitle\nInfoValue:\s.*/InfoKey:\sTitle\nInfoValue:'"$newtitle/" "$1".data.txt > "$1".data.fixed.txt;
pdftk "$1" update_info *.data.fixed.txt output "$1".fixed;
mv "$1".fixed "$1";
rm -f ./*.txt
exit;
因此,在cli上,我将输入
$> pdf标题mypdf.pdf“新标题”
pdftk创建的data.txt有多行,但是目标只有两行:
...
InfoBegin
InfoKey: Author
InfoValue: Not Me
InfoBegin
InfoKey: Title
InfoValue: Microsoft Word - Old Title.doc
InfoBegin
InfoKey: Creator
InfoValue: PScript5.dll Version 5.2
...
其中的后续行需要替换:
...
InfoKey: Title
InfoValue: Relevant New Title
...
不会产生任何错误消息,但标题保持不变。因此,似乎sed在这里有问题,但我无法弄清楚在哪里或如何。
任何帮助将不胜感激。
答案 0 :(得分:1)
这是使用Awk进行的重构,它假设pdftk
可以使用-
作为伪文件名参数来向stdin / stdout写入和读取。
#!/bin/bash
filename=$1
shift
pdftk "$filename" data_dump output - |
awk -v title="$*" '/^InfoKey: Title/ { t=1 }
t && /^InfoValue:/ { $0 = "InfoValue: " title; t=0 }1' |
pdftk "$filename" update_info - output "$filename".fixed &&
mv "$filaname".fixed "$filename"
在看到模式时设置标志变量,然后在后续行(如果设置了该变量)上执行操作的模式是一种简单且非常常见的Awk习惯用法。
不需要结尾的分号或结尾的exit
。
答案 1 :(得分:0)
@tripleee提供了使bash脚本完美运行的解决方案:
#!/bin/bash
filename=$1
shift
pdftk "$filename" data_dump output |
awk -v title="$@" '/^InfoKey: Title/ { t=1 }
t && /^InfoValue:/ { $0 = "InfoValue: " title; t=0 }1' > data.txt
pdftk "$filename" update_info data.txt output "$filename".fixed &&
mv "$filename".fixed "$filename"
rm ./data.txt