且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从文本块中提取特定行并将其存储到字符串变量中?

更新时间:2022-03-26 22:18:17

使用awk

$ fastboot oem device-id | awk 'NR==4{a=$2} NR==5{b=$2; printf "Device ID:  %s%s\n",a,b; exit}'
Device ID:  ABCDEFGH12345678ABCDEFGH1234567887654321HGFEDCBA87654321HGFEDCBA

工作原理:

  • NR == 4 {a = $ 2}

当我们到达第四行时,将第二个字段保存在变量 a 中.

When we get to the fourth line, save the second field in the variable a.

NR == 5 {b = $ 2;printf设备ID:%s%s \ n",a,b;退出}

当我们到达第五行时,将第二个字段保存在变量 b 中并写入输出行.

When we get to the fifth line, save the second field in variable b and write the output line.

$ fastboot oem device-id | sed -n 's/.* //; 4h; 5{H; x; s/\n//; s/^/Device ID:  /p}'
Device ID:  ABCDEFGH12345678ABCDEFGH1234567887654321HGFEDCBA87654321HGFEDCBA

工作原理:

  • -n

告诉sed除非我们明确要求不要打印任何内容.

Tell sed not to print anything unless we explicitly ask it to.

s/.*//

找到直到行尾的所有字符,包括最后一行,然后将其删除.

Find all characters up to and including the last space on the line and delete them.

`4h

如果我们在第四行,请保留保留空间中的剩余内容.

If we are on the fourth line, save what's left to the hold space.

5 {H;X;s/\ n//;s/^/设备ID:/p}

如果我们在第五行,请将行的剩余内容附加到保留空间( H ).将保留空间与模式空间( x )交换.删除换行符的任何换行符( s/\ n//).将字符串 Device ID:添加到模式空间的开头并打印( s/^/Device ID:/p ).

If we are on the fifth line, append what's left of the line to the hold space (H). Swap the hold space with the pattern space (x). Remove the newline any newline character (s/\n//). Add the string Device ID: to the beginning of the pattern space and print it (s/^/Device ID: /p).

$ fastboot oem device-id | grep -oE '[[:alnum:]]{32}$' | { read a; read b; echo "Device ID:  $a$b"; }
Device ID:  ABCDEFGH12345678ABCDEFGH1234567887654321HGFEDCBA87654321HGFEDCBA

工作原理:

  • grep -oE'[[:alnum:]] {32} $'

如果fastboot中的行以32个字母数字字符结尾,请打印这些字符.

If the line from fastboot ends with 32 alphanumeric characters, print those characters.

更详细地, -o 选项告诉 grep 仅打印行中匹配的部分. -E 告诉grep使用扩展的正则表达式. [[[:alnum:]] {32} 匹配32个字母数字字符. $ 仅在行尾匹配.

In more detail, the -o option tells grep to only print the matching part of a line. -E tells grep to use extended regex. [[:alnum:]]{32} matches 32 alphanumeric characters. $ matches only at the end of the line.

阅读a;读b;回声设备ID:$ a $ b";

来自 grep 的第一条输出行被读取到变量 a 中.第二行输出被读取到变量 b 中.然后,将所需的行回显到标准输出.

The first output line from grep is read into variable a. The second output line is read into variable b. Then, the desired line is echoed to standard output.