Sed

替換unix文件中的base64值

  • March 29, 2022

我有一個問題,我有一個文件 test.txt,其內容如下:

objectClass: CPM1
objectClass: CPM2
objectClass: CPM3
objectClass: CPM4
objectClass: CPZ
objectClass: CP04s
objectClass: CP0A
objectClass: CP11
entryDS: 1
nodeId: 21
createTimestamp: 20211014155438Z
modifyTimestamp: 20220313041228Z
MSISDN: 353834079137
IMSI: 272050103105233
NAM: 0
CDC: 1423
IMEISV:: U1RQJgAkQiE=
AUTHINFO: 0
CSP: 11
SUBSCSPVERS: 20
RSA: 20
SUBSRSAVERS: 19
APNID1: 4

每次找到文本 IMEISV:: 時,我都想用以下函式的結果替換該文件中 IMEISV:: 之後的值(在本例中為 U1RQJgAkQiE=):

base64 -d | od -t x8 -An | rev

如果我在 unix 中這樣做,迴聲將是這樣的:

echo U1RQJgAkQiE= | base64 -d | od -t x8 -An | rev

結果將是 3545056200422412

所以在文件的最後,值 U1RQJgAkQiE= 應該是 3545056200422412。像這樣:

objectClass: CPM1
objectClass: CPM2
objectClass: CPM3
objectClass: CPM4
objectClass: CPZ
objectClass: CP04s
objectClass: CP0A
objectClass: CP11
entryDS: 1
nodeId: 21
createTimestamp: 20211014155438Z
modifyTimestamp: 20220313041228Z
MSISDN: 353834079137
IMSI: 272050103105233
NAM: 0
CDC: 1423
IMEISV:: 3545056200422412
AUTHINFO: 0
CSP: 11
SUBSCSPVERS: 20
RSA: 20
SUBSRSAVERS: 19
APNID1: 4

有人可以讓我知道如何使用 sed/perl …嗎?我真的是unix的新手

怎麼樣

unpack("h*", decode_base64($_))

decode_base64perlMIME模組提供的位置,例如:

$ perl -MMIME::Base64 -pe 's/IMEISV:: \K(.*)$/unpack("h*", decode_base64($1))/e' test.txt
objectClass: CPM1
objectClass: CPM2
objectClass: CPM3
objectClass: CPM4
objectClass: CPZ
objectClass: CP04s
objectClass: CP0A
objectClass: CP11
entryDS: 1
nodeId: 21
createTimestamp: 20211014155438Z
modifyTimestamp: 20220313041228Z
MSISDN: 353834079137
IMSI: 272050103105233
NAM: 0
CDC: 1423
IMEISV:: 3545056200422412
AUTHINFO: 0
CSP: 11
SUBSCSPVERS: 20
RSA: 20
SUBSRSAVERS: 19
APNID1: 4

引用自:https://unix.stackexchange.com/questions/696541