我希望使用 sed 來做多個替換,這些替換位于 JSON 檔案中的 names.txt 中:
部分 JSON 檔案包含:
{
"iscomplete": true,
"totalcount": 3,
"errcount": 1,
"requser": "Username",
"fileimportreqqueueid": 3,
"format": "JSON",
"errorfile": "http://host:port/maximo/api/fileimporterrfile/3",
"_rowstamp": "1521573",
"iscancelled": false,
"reqdatetime": "2019-02-20T14:08:22-05:00",
"name": "[email protected]",
"href": "http://host:port/maximo/api/os/mxapifileimportqueue/_dGVzdGxvYzMuanNvbg--",
"pindex": 3,
"osname": "MXAPIOPERLOC"
}
和names.txt的一部分:
[email protected] Jason.Brady
[email protected] L.Robson
[email protected] Mikegraham
[email protected] Phil.Lewis
[email protected] LiamH
[email protected] James.Birch
我嘗試了以下方法:
#!/bin/bash
while read f ; do
email=`echo $f |awk '{print $1}' `
username=`echo $f|awk '{print $2}'`
sed -i 's!$email!$username!g' file.csv
done<names.txt
我該怎么做 ?
謝謝
uj5u.com熱心網友回復:
首先,讓我們將電子郵件名稱對轉換為 JSON 查找表。
jq -nR '
[ inputs | capture("^(?<key>\\S )\\s (?<value>. )") ] |
from_entries
' names.txt
這產生
{
"[email protected]": "Jason.Brady",
"[email protected]": "L.Robson",
"[email protected]": "Mikegraham",
"[email protected]": "Phil.Lewis",
"[email protected]": "LiamH",
"[email protected]": "James.Bir"
}
jqplay 上的演示
這使我們可以輕松處理主檔案。
jq --argjson fixes "$(
jq -nR '
[ inputs | capture("^(?<key>\\S )\\s (?<value>. )") ] |
from_entries
' names.txt
)" '.name |= ( $fixes[.] // . )' data.json
或者
# Accomodates a large name mapping file, but requires bash.
jq --argfile fixes <(
jq -nR '
[ inputs | capture("^(?<key>\\S )\\s (?<value>. )") ] |
from_entries
' names.txt
) '.name |= ( $fixes[.] // . )' data.json
jqplay 上的演示
你說你只提供了 JSON 檔案的一部分,所以你必須相應地調整程式。例如,如果你有
[ {...}, {...}, {...} ]
你會替換
.name |= ( $fixes[.] // . )
和
.[].name |= ( $fixes[.] // . )
jqplay 上的演示
uj5u.com熱心網友回復:
我建議看一下-fGNU 的選項sed,它后面應該跟有替換檔案的名稱,在您的情況下,您可以創建replacements.sed具有以下內容的檔案
s/jason\.brady@doom\.com/Jason.Brady/g
s/linda\.ribson@doom\.com/L.Robson/g
s/Mike\.graham@doom\.com/Mikegraham/g
s/Phill\.Lewis@doom\.com/Phil.Lewis/g
s/Liam\.Haggard@doom\.com/LiamH/g
s/James\.birch@doom\.com/James.Birch/g
接著
sed -f replacements.sed <file.json
file.json帶有 JSON 的檔案名在哪里。輸出將是應用了替換的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/383844.html
