在shell脚本中提取引号中的单词

发布于 2024-09-29 22:24:55 字数 456 浏览 4 评论 0原文

我正在制作一个 shell 脚本,它将自动执行 Arch Linux AUR 软件包 的安装过程。我需要列出包的所有依赖项(以检查它们是否已安装),它们在安装脚本中看起来像这样:

depends=('sdl' 'libvorbis' 'openal')

我能想到的最简单的方法(或唯一想法)是像这样:

grep "depends" PKGBUILD | awk -F"'" '{print $2 "\n" $4 "\n" $6;}'

但是依赖项计数因包而异。那么,如果字数不同,如何输出引号中的名称呢?

预先感谢,

-skazhy

I am making a shell script that will automate the install process of Arch Linux AUR packages. I need to list all dependencies of the package (to check if they are installed), they appear like this in install script:

depends=('sdl' 'libvorbis' 'openal')

The easiest way (or the only idea) that I could come up with is something like this:

grep "depends" PKGBUILD | awk -F"'" '{print $2 "\n" $4 "\n" $6;}'

But the dependency count varies from package to package. So, how I output the names in quotes if the word count is varying?

Thanks in advance,

-skazhy

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

落日海湾 2024-10-06 22:24:55

如果 depends 只是一行,您可以尝试的一件事是在 bash 本身中评估该行...这将导致一个名为“depends”的数组,其中包含所有值。看起来很棘手,但对于动态语言来说并非如此:

depend_line=`grep depends $PKGBUILD`
eval "${depend_line}"
echo ${depend[0]} # Will print sdl in your example

If the depends is just one line, one thing you may try is to evaluate the line in bash itself... This will lead to an array called "depends" that holds all the values. Seems tricky, but not with dynamic languages:

depend_line=`grep depends $PKGBUILD`
eval "${depend_line}"
echo ${depend[0]} # Will print sdl in your example
黯然#的苍凉 2024-10-06 22:24:55

您可以避免使用 eval 或使用 declare 获取临时文件的安全问题:

declare -a "$(grep "depends" PKGBUILD)"

这将创建一个名为“depends”的数组,其中包含“sdl”、“libvorbis”和基于示例数据的“openal”。

You can avoid the security issues of using eval or sourcing a temporary file by using declare:

declare -a "$(grep "depends" PKGBUILD)"

This will create an array called "depends" containing "sdl", "libvorbis" and "openal" based on the example data.

美人迟暮 2024-10-06 22:24:55

试试这个大小:

grep "depends" PKGBUILD > /tmp/depends
. /tmp/depends

echo ${depends[@]}

嘿看,那是一个数组吗?是的。

for d in "${depends[@]}" ; do
    printf '"%s"' "$d"
done

注意:在真实的脚本中,您需要更加小心地命名临时文件。

Try this on for size:

grep "depends" PKGBUILD > /tmp/depends
. /tmp/depends

echo ${depends[@]}

Hey look, is that an array? Yes it is.

for d in "${depends[@]}" ; do
    printf '"%s"' "$d"
done

Note: In a real script you'd want to be more careful with the naming of the temporary file.

与酒说心事 2024-10-06 22:24:55

你可以这样做:

grep "depends" PKGBUILD | perl -e "while(<>){print \"\$1\\n\" while m/'.{-}'/g;}"

You could do something like:

grep "depends" PKGBUILD | perl -e "while(<>){print \"\$1\\n\" while m/'.{-}'/g;}"
属性 2024-10-06 22:24:55

awk -F"'" '{for(i=2;i<=NF;i+=2) print($i)}'

awk -F"'" '{for(i=2;i<=NF;i+=2) print($i)}'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文