如何使用 Bash 读取特定行和特定字段?
我有这个文件,我只想获取 testme= 的值,以便我可以执行另一个操作。但这会抛出很多行,实际上还无法使其工作。
1.test.sh
#!/bin/bash
for i in $(cat /var/tmp/test.ini); do
# just one output i need: value1
grep testme= $i
done
2./var/tmp/test.ini
; comments
testme=value1
; comments
testtwo=value2
I have this file and i want to only get the value of testme= So that i can do another action. But this throws lots of lines and actually cant yet make it work.
1. test.sh
#!/bin/bash
for i in $(cat /var/tmp/test.ini); do
# just one output i need: value1
grep testme= $i
done
2. /var/tmp/test.ini
; comments
testme=value1
; comments
testtwo=value2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
怎么样
或者只是使用 bash
How about
or alternatively just using bash
我检查了你的代码,问题出在你的for循环中。
您实际上读取了文件的每一行,并将其交给 grep,这是不正确的。我猜你有很多行有错误,
(或类似的东西)。
你应该给 grep 你的文件名。 (没有 for 循环)
例如
I checked your codes, the problem is in your for loop.
you actually read each line of the file, and give it to grep, which is NOT correct. I guess you have many lines with error,
(or something like that).
you should give grep your file name. (without the for loop)
e.g.
grep 删除注释,然后 awk 查找变量并打印其值。或者,在 awk 行中执行同样的操作:
The grep removes comments, then awk finds the variable and prints its value. Or, same thing in a single awk line:
这个怎么样?
我们找到该行,然后删除前缀,只留下值。 Grep 为我们进行迭代,无需明确。
How about this?
We find the line and then remove the prefix, leaving only the value. Grep does the iterating for us, no need to be explicit.
awk 可能是正确的工具,但由于问题似乎暗示您只想使用 shell,因此您可能需要类似的东西:
awk is probably the right tool for this, but since the question does seem to imply that you only want to use the shell, you probably want something like: