I have written a bash script that is supposed to get version number of ghostscript. The code looks like this:

local str=$(gs -v)
local gs_version=''
if [ -n "$str" ] ; then
  gs_version=`awk -F'|' 'Ghostscript/ {version=$3; print version}' $str`
fi
echo " version: $gs_version"

The result of gs -v is:

GPL Ghostscript 8.70 (2009-07-31)
Copyright (C) 2009 Artifex Software, Inc.  All rights reserved.

The script is looking for the word Ghostscript and is trying to extract the third word which is 8.70. That is my objective.

I am not an awk expert, but when I run this code I get the following error:

awk: Ghostscript/ {version=$3; print version}
awk:              ^ syntax error

I guess I must be going blind as I don't see what is wrong. I thought I had this working on Ubuntu but when I try it on CentOS 6 this is what I get.

有帮助吗?

解决方案

You can say:

awk '/Ghostscript/{print $3}' inputfile

to get the third field from the line containing Ghostscript.

When you say:

gs_version=`awk -F'|' 'Ghostscript/ {version=$3; print version}' $str`

there is:

  • a missing / before Ghostscript
  • moreover, since you want awk to read from a string you need to make use of herestring.
  • fields are delimited by whitespace by default so you don't need to supply one (not sure why you used |, though)
gs_version=$(awk '/Ghostscript/ {version=$3; print version}' <<< "$str")

Although there was simpler ways to get the version information.

其他提示

As an alternative you can use grep -P to grab that version string:

gs -v | grep -oP '(?<=Ghostscript )\S+'
8.70
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top