Я сжимаю свой pdf-файл, используя ghostscript, который выдает ошибку на защищенном паролем случае, с которым я должен обращаться.Как grep для шаблона строки из вывода команды в сценарии оболочки?
Shell скрипт
GS_RES=`gs -sDEVICE=pdfwrite -sOutputFile=$gsoutputfile -dNOPAUSE -dBATCH $2 2>&1`
if [ "$GS_RES" != "" ]
then
gspassmsg="This file requires a password for access"
echo "Error message is :::::: "$GS_RES
gspassworddoc=`awk -v a="$GS_RES" -v b="$gspassmsg" 'BEGIN{print index(a,b)}'`
if [ $gspassworddoc -ne 0 ]
then
exit 3 #error code - password protected pdf
fi
fi
И мое GS_RES
значение после выполнения команды, как следующий
Сообщение об ошибке 1:
GPL Ghostscript 9.19 (2016-03-23) Copyright (C) 2016 Artifex Software, Inc. All
rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for d
etails. Error: /syntaxerror in -file- Operand stack: Execution stack: %interp_ex
it .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --n
ostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1967 1 3 %opa
rray_pop 1966 1 3 %oparray_pop 1950 1 3 %oparray_pop 1836 1 3 %oparray_pop --nos
tringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringva
l-- 2 %stopped_push Dictionary stack: --dict:1196/1684(ro)(G)-- --dict:0/20(G)--
--dict:78/200(L)-- Current allocation mode is local Current file position is 1
Сообщение об ошибке 2:
GPL Ghostscript 9.19 (2016-03-23) Copyright (C) 2016 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html Error: Cannot find a 'startxref' anywhere in the file. Output may be incorrect. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html Error: An error occurred while reading an XREF table. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html The file has been damaged. This may have been caused gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html by a problem while converting or transfering the file. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html Ghostscript will attempt to recover the data. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html However, the output may be incorrect. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html Error: Trailer dictionary not found. Output may be incorrect. No pages will be processed (FirstPage > LastPage). gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html This file had errors that were repaired or ignored. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html Please notify the author of the software that produced this gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html file that it does not conform to Adobe's published PDF gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html specification. gs.pdf gsempty.pdf new_sathishks_protected.html sathishks_protected.html The rendered output from this file may be incorrect.
При управлении AWK на сообщение об ошибке 2
gspassmsg="This file requires a password for access"
gspassworddoc=`awk -v a="$GS_RES" -v b="$gspassmsg" 'BEGIN{print index(a,b)}'`
Он бросает мне следующую ошибку
Ошибка: awk: newline in string GPL Ghostscript 9.19... at source line 1
Сообщение об ошибке 3
**** Error: Cannot find a 'startxref' anywhere in the file.
**** Warning: An error occurred while reading an XREF table.
**** The file has been damaged. This may have been caused
**** by a problem while converting or transfering the file.
**** Ghostscript will attempt to recover the data.
**** Error: Trailer is not found.
**** This file had errors that were repaired or ignored.
**** Please notify the author of the software that produced this
**** file that it does not conform to Adobe's published PDF
**** specification.
я не мог захватить эту ошибку с фрагментом из нижеследующего ответа
if ! gs_res=$(gs -sDEVICE=pdfwrite -sOutputFile="$gsoutputfile" -dNOPAUSE -dBATCH "$2" 2>&1 1>/dev/null); then
echo "Error message is :::::: $gs_res" >&2
gspassmsg='This file requires a password for access'
[[ $gs_res == *"$gspassmsg"* ]] && exit 3 # password protected pdf
echo "Some other error !"
fi
Просьба разъяснить мне следующее
- Почему
awk
ведет себя странно здесь? Что мне не хватает? - Как grep для шаблона в строке, содержащей специальные символы?
- Имеет ли Ghostscript какие-либо предопределенные сообщения об ошибках? Если возможно, предложите какую-либо документацию для ссылки.
- Можно ли сжать защищенный паролем pdf-файл с помощью ghostscript?
- Как я могу обеспечить успех сжатия gs в вышеуказанном случае? Так как я могу не знать о различной возможной ошибке, которую Ghostscript может бросить, чтобы я мог перекреститься с моим результатом выполнения команды.
Я совершенно новый для этого сценария оболочки. Кто-нибудь, пожалуйста, помогите мне в этом.
PS: Я редактировал свой вопрос с дополнительной информацией. Пожалуйста, изучите его. Если что-то нужно добавить, я добавлю его.
@ mklement0 ищет строку (например, «Этот файл требует доступа к доступу») из выходного файла команды - передал этот процесс как «grep». – lsof
И я не уверен, что думаю, что 'awk' играет в проводку, когда мой вывод команды содержит в себе некоторые специальные символы. – lsof
Специальные символы похожи на (',") в выходном файле команды - который я добавил в сообщении об ошибке 2. Пожалуйста, загляните в него. – lsof