我有一个像这样的文件:
some line
some other line
DisplayChoices=SAMSUNG
yet another line
ChipManufacturer=LG
and yet another line
(文件中可能有更多行,但符号=
是唯一的,仅出现在我想要执行操作的行中)
现在,我需要将后面的字符串转换=
为十六进制表示形式,所以最终它应该看起来像
some line
some other line
DisplayChoices=53,41,4D,53 (etcetera, hex representation, seperated by comma`s)
yet another line
ChipManufacturer=4C,47
and yet another line
我尝试了 sed 和 od 但无济于事,od
处理了完整的文件,但我只需要转换指定的字符串。有人知道解决办法吗?
答案1
如果 Perl 是一个选项:
$ perl -lpe 's#(?<==)(.*)#join ",", unpack("H2" x length($1), $1)#e' file
some line
some other line
DisplayChoices=53,41,4d,53,55,4e,47
yet another line
ChipManufacturer=4c,47
and yet another line
我相信这可以改进......
答案2
您可以通过设置 awk 数组将字节转换为十六进制来避免外部进程调用:
AWK='''
BEGIN {
FS = "="; OFS = "=";
for (j = 0; j < 256; j++)
Hx[sprintf("%c",j)] = sprintf(",%.2X", j);
}
function toHex (tx, Local, j, r) {
for (j = 1; j <= length (tx); j++)
r = r Hx[substr(tx, j, 1)];
return (substr(r, 2));
}
$2 != "" { $2 = toHex( $2); }
{ print; }
'''
awk "${AWK}" myFile
paul--) awk "${AWK}" foo.txt
some line
some other line
DisplayChoices=53,41,4D,53,55,4E,47
yet another line
ChipManufacturer=4C,47
and yet another line
ESC,%,TAB,*=1B,25,09,2A
答案3
可能不是最干净的方法,但是awk
:
awk -F= -v OFS=\= '$2 != ""{
"printf "$2" | od -A n -t x1 | tr -s \" \"" | getline $2;
gsub(/^ | $/,"",$2);
gsub(/\s/, ",",$2);
}1' input
这将用作=
字段分隔符,如果存在第二个字段,它将od -A n -t x1
对其执行,压缩所有空格,修剪前导和尾随空格,并将所有剩余空格转换为逗号。