如何从 bash 变量回显/打印特定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15777232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I echo/print specific lines from a bash variable
提问by lacrosse1991
I am trying to print specific lines from a multi-line bash variable. I've found the following:
我正在尝试从多行 bash 变量打印特定行。我发现了以下内容:
while read line; do echo LINE: "$line"; done <<< "$x"
where x would be the variable, but that simply prints out all lines instead of just a single one (say line 1 for instance). How could I go about adapting this to print out a specific line instead of all of them? (would like to avoid having to write the variable to a file instead)
其中 x 将是变量,但这只是打印出所有行而不是单行(例如第 1 行)。我该如何调整它以打印出特定的行而不是所有的行?(希望避免将变量写入文件)
回答by William Pursell
To print the Nth line:
打印第 N 行:
sed -n ${N}p <<< "$x"
or (more portably):
或(更便携):
sed -n ${N}p << EOF
$x
EOF
or
或者
echo "$x" | sed -n "$N"p
or
或者
echo "$x" | sed -n ${N}p
or (for the specific case N==3)
或(对于特定情况 N==3)
echo "$x" | sed -n 3p
or
或者
while read line; do echo LINE: "$line"; done <<< "$x" | sed -n ${N}p
or
或者
while read line; do echo LINE: "$line"; done << EOF | sed -n ${N}p
$x
EOF
回答by FatalError
You can split it into an array like:
您可以将其拆分为一个数组,例如:
IFS=$'\n' lines=($x)
Then you can access any line by indexing the array, e.g.:
然后您可以通过索引数组来访问任何行,例如:
echo ${lines[1]}
(of course, lines[0]
is "line 1").
(当然lines[0]
是“第1行”)。
回答by ghoti
If you don't want to use an array for some reason, and you want to do this within bash rather than by spawning an external tool like sed
, you can simply count lines:
如果您出于某种原因不想使用数组,并且您想在 bash 中执行此操作而不是通过生成外部工具(如 )sed
,则可以简单地计算行数:
[ghoti@pc ~]$ x=$'one\ntwo\nthree\nfour\nfive\n'
[ghoti@pc ~]$ n=3
[ghoti@pc ~]$ for (( c=0; c<n; c++ )); do read line; done <<< "$x"
[ghoti@pc ~]$ echo $line
three
[ghoti@pc ~]$
Or using one fewer variable:
或者少使用一个变量:
[ghoti@pc ~]$ n=2
[ghoti@pc ~]$ for (( ; n>0; n-- )); do read line; done <<< "$x"
[ghoti@pc ~]$ echo $line
two
These methods use what's sometimes called a "three expression for loop". It's a construct that's common in many languages, from bash to awk to perl to PHP to C (but not Python!). Getting to know them will help your programming in general.
这些方法使用有时称为“循环的三个表达式”的方法。这是一种在许多语言中都很常见的结构,从 bash 到 awk 到 perl,再到 PHP 到 C(但不是 Python!)。了解它们将有助于您的编程。
Though ... you probably don't want to be using bash to learn "real" programming. :-)
虽然……您可能不想使用 bash 来学习“真正的”编程。:-)