[英]Reading the contents of a text file and assign to a variable using bash script
[英]Bash script find certain text in a file.dev and assign it to a variable
我有一个 file.dev 包含以下内容:
1 DEVICES {
2 GLOBAL-CONFIG {
3 framerate = "20000";
4 subframes = "0";
5 max_consec_timeouts = "10";
6 max_total_timeouts = "1000";
7 schedmode = "Standard";
8 clustermode = "Standard";
9 }
10 IO-DEVICES {
11 }
12 COMPUTING-DEVICES {
13 RT_WORKSTATION FDT-C-XM-0120 = {
14 hostname = "FDT-C-XM-0120";
15 ipaddress = "fdt-c-XM-0120.fdtel.exter";
16 DISPLAYS {
17 main = "FDT-C-XM-0120:0.0";
18 }
19 SCHEDPARAM {
20 active = "0";
21 framerate = "20000";
22 subframes = "0";
23 max_consec_timeouts = "10";
24 max_total_timeouts = "1000";
25 }
26 }
27
28 RT_HOST fdt-c-agx-0008 = {
29 hostname = "fdt-c-agx-0008";
30 ipaddress = "fdt-c-agx-0008";
31 SCHEDPARAM {
32 active = "0";
33 framerate = "20000";
34 subframes = "0";
35 max_consec_timeouts = "10";
36 max_total_timeouts = "1000";
37 }
38 }
39
40 # RT_HOST fdt-c-agx-0003 = {
41 # hostname = "fdt-c-agx-0003";
42 # ipaddress = "fdt-c-agx-0003.fdtel.exter";
43 # SCHEDPARAM {
44 # active = "0";
45 # framerate = "20000";
46 # subframes = "0";
47 # max_consec_timeouts = "10";
48 # max_total_timeouts = "1000";
49 # }
50 # }
51 }
52 }
此文件位于目录C:/TechSAT/ADS2/config/file.dev
如您所见,变量hostname
有三个条目(line 14, 29 and 41)
。
我要做的是编写一个 bash 脚本,该脚本仅找到第一个条目(line 14)
并将其值FDT-C-XM-0120
保存在像$hostnameValue = FDT-C-XM-0120
这样的变量中以进行测试目的。
我实际上找到了一个半可行的解决方案,例如:
var=$(grep -r 'hostname' C:/TechSAT/ADS2/config/devices.dev)
但是,这会打印所有匹配项,例如
hostname = "FDT-C-VM-0120";
hostname = "fdt-c-agx-0008";
# hostname = "fdt-c-agx-0003";
在我的情况下, var
必须包含第一个匹配项的值,即FDT-C-XM-0120
提前致谢
Awk 可以为所欲为。
awk -F'"' '/hostname/{print $2 ; exit}' file.txt
Output
FDT-C-XM-0120
使用 GNU grep
并cut
grep -m1 'hostname' file.txt | cut -d'"' -f2
两种解决方案都使用双引号"作为分隔符,使用awk
-F'"'
和cut
-d'"'
双引号需要转义,使用\
或用单引号将其括起来' 。所以它可以写为-F\"
和-d\"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.