【问题标题】:How do I use sed to store a variable?如何使用 sed 存储变量?
【发布时间】:2021-01-30 12:36:00
【问题描述】:

我正在尝试使用 sed 作为变量的输入。用户将从文件列表中选择,每个文件之前都有数字来标识单个文件。然后他们选择一个与名称相对应的数字。我需要获取该文件的名称。我的代码是:

for entry in *; do
((i++))
echo "$i) $entry: "
done

echo What file # do you want to choose?:
read filenum
fileName=$(./myscript.sh | sed -n "${filenum}p")
echo $fileName  ###this is to see if anything goes into fileName. nothing is ever output
echo What do you want to do with $fileName?

理想情况下,我会使用 () 而不是反引号,但我似乎无法弄清楚如何使用。我查看了下面的链接,但无法让这些想法发挥作用。我相信一个问题可能是我试图在我的 sed 中包含 filenum 变量。

https://www.linuxquestions.org/questions/linux-newbie-8/storing-output-of-sed-in-a-variable-in-shell-script-499997/

Store output of sed into a variable

【问题讨论】:

  • 在此处搜索 [bash] select done 并阅读有关 select 命令的 bash 手册(在线)。 stackoverflow.com/questions/64130687/… 是最近出现的一个很好的例子。祝你好运。
  • 你不应该在$filenum周围有反引号
  • 如果我删除 $filenum 周围的反引号,则输出变为 - sed: 1: "2": command expected
  • 当然。打印第 2 行的命令是 2p,而不仅仅是 2
  • 为什么要打印一行shell脚本?您真的要打印脚本输出的选定行吗?

标签: bash shell variables sed terminal


【解决方案1】:

不要在$filenum 周围加上反引号。这将尝试将$filenum 的内容作为命令执行。将变量放在双引号内。

如果你确实想在另一组反引号中嵌套一个反引号表达式,你必须将它们转义。这就是$() 发挥作用的地方——它们可以轻松嵌套。

当您使用sed -n 时,您需要使用p 命令打印您想要在输出中显示的行。

fileName=$(sed -n "${filenum}p" myscript.sh)

这会将$filenummyscript.sh 行的内容放入变量中。

如果您真的想执行myscript.sh 并打印其输出的选定行,则需要通过管道传送到sed

fileName=$(./myscript.sh | sed -n "${filenum}p")

【讨论】:

  • 管道不工作。在我输入像“3”这样的数字后,没有输出。它应该是一个文件名?
  • 您确定脚本至少有 3 行输出吗?
  • 您可以在问题中添加myscript.sh 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
  • 2019-03-10
  • 2013-04-25
  • 2015-05-24
  • 2017-07-31
  • 2022-01-08
相关资源
最近更新 更多