I try to get a line by a giving number in a variable so i try awk command:
我尝试通过变量中的给定数字得到一行,所以我尝试awk命令:
i did :
我做了:
DATE_ISSUE_OPIT_SIP="31456
12390
11232
12222"
COUNTER_NUMBER=1
line=$(awk 'NR==$COUNTER_NUMBER' <<< "$Date_ISSUE_OPIT_SIP")
Output is empty.
输出为空。
I want the output like this for example :
我希望输出像这样:
COUNTER_NUMBER=2
line=$(awk 'NR==$COUNTER_NUMBER' <<< "$Date_ISSUE_OPIT_SIP")
echo $line
11232
Thank's for help
感谢帮助
3 个解决方案
#1
1
The simplest fix will be replacing single quotes with double quotes
最简单的修复方法是用双引号替换单引号
... awk "NR==$COUNTER_NUMBER" <<< "$DATE_ISSUE_OPIT_SIP"
note also that the variable names you used didn't match, it's case sensitive.
另请注意,您使用的变量名称不匹配,它区分大小写。
#2
1
Awk has a wonderly easy way of setting an internal variable by passing it on the command line:
通过在命令行上传递内部变量,awk有一种非常简单的方法来设置内部变量:
txt="31456
12390
11232
12222"
n=2
line=$(awk 'NR==counter' counter=$n <<< "$txt")
echo "$line"
12390
It also means you can't easily have a file with an =
in the name.
这也意味着您不能轻易拥有名称中带有=的文件。
You can also do:
你也可以这样做:
line=$(awk -v counter=$n 'NR==counter' <<< "$txt")
Note: NR
starts at 1. So to get the 3rd line, you would pass 3 in your example.
注意:NR从1开始。因此,要获得第3行,您将在示例中传递3。
#3
0
It's OK with sed too
sed也没问题
sed "$COUNTER_NUMBER"'!d' <<< "$DATE_ISSUE_OPIT_SIP"
#1
1
The simplest fix will be replacing single quotes with double quotes
最简单的修复方法是用双引号替换单引号
... awk "NR==$COUNTER_NUMBER" <<< "$DATE_ISSUE_OPIT_SIP"
note also that the variable names you used didn't match, it's case sensitive.
另请注意,您使用的变量名称不匹配,它区分大小写。
#2
1
Awk has a wonderly easy way of setting an internal variable by passing it on the command line:
通过在命令行上传递内部变量,awk有一种非常简单的方法来设置内部变量:
txt="31456
12390
11232
12222"
n=2
line=$(awk 'NR==counter' counter=$n <<< "$txt")
echo "$line"
12390
It also means you can't easily have a file with an =
in the name.
这也意味着您不能轻易拥有名称中带有=的文件。
You can also do:
你也可以这样做:
line=$(awk -v counter=$n 'NR==counter' <<< "$txt")
Note: NR
starts at 1. So to get the 3rd line, you would pass 3 in your example.
注意:NR从1开始。因此,要获得第3行,您将在示例中传递3。
#3
0
It's OK with sed too
sed也没问题
sed "$COUNTER_NUMBER"'!d' <<< "$DATE_ISSUE_OPIT_SIP"