我正在嘗試從 Slack 的 channels.json 檔案中的 json 物件串列中清除不活動的頻道。我通過檢查匯出中通道目錄中最后一條訊息的時間戳并將非活動通道串列寫入陣列,從而獲得了非活動通道串列(定義為在過去 90 天內未更新) json 物件本身。唯一的問題是我不知道如何安排它,以便在寫入新的輸出檔案之前從輸入中洗掉陣列中的每個通道。請參閱missing something important here下面我的函式代碼中的注釋。
這是我目前的功能。
exclude-inactive-channels () {
# Check for a valid argument
if [ -z $1 ]; then
echo "No arguments supplied."
return 1
elif [ $# -gt 1 ]; then
echo "Too many arguments supplied."
return 1
elif [ ! -f $1 ]; then
echo "File doesn't exist."
return 1
fi
cutoff_epoch=$(gdate -d "90 days ago" '%s')
inactive_channels=()
for channel in $(jq -r '.[] | select(.is_archived == false) | .name' $1); do
if [[ -d $channel ]]; then
last_post=$(ls -1 $channel |sort -n |tail -1 |awk -F'.' '{print $1}')
last_post_epoch=$(gdate -d "$last_post" '%s')
if [[ $last_post_epoch -lt $cutoff_epoch ]]; then
inactive_channels =("$channel")
echo -n "Removing $channel directory. Last post is $last_post."
#rm -rf $channel
echo -e "\033[0;32m[OK]\033[0m"
fi
fi
done
echo "Removing inactive channels from $1 and writing output to new-$1."
for inactive_channel in ${inactive_channels[@]}; do
# Next line is untested pseudo code
jq -r '.[] | del(.name == $inactive_channel)' $1 #missing something important here
done | jq -s > new-${1}
echo "Replacing $1 with new-$1."
# mv new-${1} $1
}
呼叫這個函式:
exclude-inactive-channels channels.json
示例輸入:
[
{
"id": "",
"name": "announcements",
"created": 1500000000,
"creator": "",
"is_archived": false,
"is_general": true,
"members": [
"",
],
"pins": [
{
"id": "",
"type": "C",
"created": 1500000000,
"user": "",
"owner": ""
},
],
"topic": {
"value": "",
"creator": "",
"last_set": 0
},
"purpose": {
"value": "company wide announcements",
"creator": "",
"last_set": 1500000000
}
},
{
"id": "",
"name": "general",
"created": 1500000000,
"creator": "",
"is_archived": false,
"is_general": true,
"members": [
"",
],
"pins": [
{
"id": "",
"type": "C",
"created": 1500000000,
"user": "",
"owner": ""
},
],
"topic": {
"value": "",
"creator": "",
"last_set": 0
},
"purpose": {
"value": "general",
"creator": "",
"last_set": 1500000000
}
},
]
uj5u.com熱心網友回復:
更有效的是將所有頻道提供給 jq 一次洗掉,而不是一次洗掉一個。
# you need to comment one of these out for out.json to not be an empty list
inactive_channels=(
"announcements"
"general"
)
jq --rawfile inactive_channel_stream <(printf '%s\0' "${inactive_channels[@]}") '
# generate an object mapping keys to delete to a truthy value
INDEX($inactive_channel_stream | split("\u0000")[]; .) as $inactive_channels
| map(select(($inactive_channels[.name] // false) | not))
' <in.json >out.json
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352415.html
