如何将文件中的引用文本隔离到 shell 变量?

发布于 2024-11-08 19:32:15 字数 1132 浏览 5 评论 0原文

如何将文件中的引用文本隔离到 shell 变量?
另外:如何忽略以 '#' 开头的行?

假设我有文本文件

8723 "full name" "more data here"
#5002 "another name" "bla bla bla"
7129 "single" blablabla
3910 noquote "bla bla bla"

,并且我想编写一个

#!/bin/sh
myscript <KEY> "<FULL NAME>" "<MORE DATA>"

针对文本文件中的每一行 执行的脚本.
如果这样更容易,您可以假设文本文件中的 FULLNAME 和 MOREDATA 始终用引号引起来,即使它们由单个单词组成。


我尝试了简单的方法

#!/bin/sh
while read key name extra
do
    echo "myscript $key \"$name\" -- \"$extra\""
    #myscript $key "$name" "$extra"
done < list.txt

,但它没有将引号内的值分组到单个 shell 变量中。
输出是

myscript 8723 ""full" -- "name" "more data here""
myscript #5002 ""another" -- "name" "bla bla bla""
myscript 7129 ""single"" -- "blablabla"
myscript 3910 "noquote" -- ""bla bla bla""

相反,我想获得

myscript 8723 "full name" -- "more data here"
myscript 7129 "single" -- "blablabla"
myscript 3910 "noquote" -- "bla bla bla"

当然,我可以将 myscript 添加到原始文本文件的每一行,并使该文件成为脚本或编写 C 程序来做到这一点...

How do I isolate quoted text from a file to a shell variable?
Also: how do I ignore lines starting with '#'?

Let's say I have the text file

8723 "full name" "more data here"
#5002 "another name" "bla bla bla"
7129 "single" blablabla
3910 noquote "bla bla bla"

and I want to write a script that executes

#!/bin/sh
myscript <KEY> "<FULL NAME>" "<MORE DATA>"

for each line in the text file.
If it makes it easier, you can assume FULLNAME and MOREDATA in the text file are always enclosed in quotes, even when they're composed of a single word.


I tried the simple

#!/bin/sh
while read key name extra
do
    echo "myscript $key \"$name\" -- \"$extra\""
    #myscript $key "$name" "$extra"
done < list.txt

but it doesn't group the value inside quotes in a single shell variable.
The output is

myscript 8723 ""full" -- "name" "more data here""
myscript #5002 ""another" -- "name" "bla bla bla""
myscript 7129 ""single"" -- "blablabla"
myscript 3910 "noquote" -- ""bla bla bla""

Instead, I'd like to obtain

myscript 8723 "full name" -- "more data here"
myscript 7129 "single" -- "blablabla"
myscript 3910 "noquote" -- "bla bla bla"

Of course I can add myscript to every line of the original text file and make that file a script or write a C program to do that ...

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

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

发布评论

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

评论(2

吖咩 2024-11-15 19:32:15
#!/bin/sh
while read key name extra
do
    eval myscript $key $name $extra
done <(grep -v "^#" list.txt)
#!/bin/sh
while read key name extra
do
    eval myscript $key $name $extra
done <(grep -v "^#" list.txt)
乞讨 2024-11-15 19:32:15
sed -e '/^[^#]/s/^/myscript /' list.txt

编辑:运行它:

sed -e '/^[^#]/s/^/myscript /' list.txt | bash
sed -e '/^[^#]/s/^/myscript /' list.txt

EDIT: To run it:

sed -e '/^[^#]/s/^/myscript /' list.txt | bash
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文