sh读取文件并在shell中采用特定值

时间:2018-11-05 12:38:13

标签: shell

我需要读取一个json文件并获取99XXXXXXXXXXXX0cccs之类的值,并在csv中写入具有列BASE_NoSchedule的csv。

输入文件:classedFFDCD_5666_4888_45_2018_02112018012106.021.json

"bfgft":"99XXXXXXXXXXXX0","fp":"XXXXXX","cur_gt":225XXXXXXXX0,"cccs"
"bfgft":"21XXXXXXXXXXXX0","fp":"XXXXXX","cur_gt":225XXXXXXXX0,"nncs"
"bfgft":"56XXXXXXXXXXXX0","fp":"XXXXXX","cur_gt":225XXXXXXXX0,"fgbs"
"bfgft":"44XXXXXXXXXXXX0","fp":"XXXXXX","cur_gt":225XXXXXXXX0,"ddss"
"bfgft":"94XXXXXXXXXXXX0","fp":"XXXXXX","cur_gt":225XXXXXXXX0,"jjjs"

预期输出:

BASE_No,Schedule
99XXXXXXXXXXXX0,cccs
21XXXXXXXXXXXX0,nncs
56XXXXXXXXXXXX0,fgbs
44XXXXXXXXXXXX0,ddss
94XXXXXXXXXXXX0,jjjs

我正在使用以下代码读取文件名和日期,但无法读取BASE_NoSchedule的文件。

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for line in `ls -lrt *.json`; do
        date=$(echo $line |awk -F ' ' '{print $6" "$7}');
        file=$(echo $line |awk -F ' ' '{print $9}');
        echo ''$file','$(date "+%Y/%m/%d  %H.%M.%S")'' >> $File_Tracker`

2 个答案:

答案 0 :(得分:0)

假设json的结构并非每一行都发生变化,则示例代码逐行检查以获取特定值,并使用printf进行连接。然后将输出存储为新的output.txt文件。

#!/bin/bash
input="/home/kj4458/winhome/Downloads/sample.json"
printf "Base,Schedule \n" > output.txt
while IFS= read -r var
do
        printf "`echo "$var" | cut -d':' -f 2 | cut -d',' -f 1`,`echo "$var" | cut -d':' -f 4 | cut -d',' -f 2` \n" | sed 's/"//g' >> output.txt
  done < "$input"

答案 1 :(得分:0)

awk -F“ \”“'{print $ 4”,“ $ 12}”文件

99XXXXXXXXXXXX0,cccs

21XXXXXXXXXXXX0,nncs

56XXXXXXXXXXXX0,fgbs

44XXXXXXXXXXXX0,ddss

94XXXXXXXXXXXX0,jjjs

我得到了那个结果!