我在YAML文件中有数据如下:
report_id:youtube
columns:
- date
- channel_id
- video_id
- claimed_status
- uploader_type
- live_or_on_demand
- subscribed_status
report_id:device
columns:
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes
以及许多此类report_ids及其列信息。
我编写了一个脚本,根据shell脚本中传递的report_id将列写入另一个输出文件。以下是一个例子:
copy_fields()
{
report_id=`cat $FILE | grep 'report_id: device' | awk '{print $NF}'`
echo "copy $report_id" > $OUTPUT
echo "(" >> $OUTPUT
for i in `cat $FILE | grep - | awk '{print $NF}'`
do
echo $i
echo $i >> $OUTPUT
done
echo ")" >> $OUTPUT
}
copy_fields
上面的列应该只将设备信息写入文件"输出"但它将所有数据写入"输出"提交如下文件:
- date
- channel_id
- video_id
- claimed_status
- uploader_type
- live_or_on_demand
- subscribed_status
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes
脚本应该将数据写入"输出"文件基于report_id传递,如果设备被传递,它应该写入"输出"如下:
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes.
请帮助我获取确切的代码。我需要编写一个shell脚本,通过传递report_id从yaml文件读取数据,并能够将该数据写入另一个带有report_id列的输出文件。
答案 0 :(得分:0)
您可以尝试以下awk脚本
key='device'
awk -v key=$key '{if(/report_id/){val=$0}else{if(val ~ key){FS=""; print $0}}}' input
输出
columns:
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes
答案 1 :(得分:0)
试试这个awk!
awk -v pat=$a 'c&&!--c{next};($0==pat){p=1;c=1;next} p&&/^report_id:/{p=0};p' file
或
awk -v pat="report_id:whatever" 'c&&!--c{next};($0==pat){p=1;c=1;next} p&&/^report_id:/{p=0};p' file
输出:
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes
$ a =" report_id:device"或" report_id:youtube"或者其他..可以在bash脚本中声明
答案 2 :(得分:0)
运行 ./ script.sh设备文件输出
Argumnet 1 report_id
参数2文件
参数3 OUTPUT文件
<强> script.sh 强>
#! /bin/bash
report=$1
file=$2
awk -vrep="$report" 'BEGIN{rep="report_id:"rep} flag && /^report_id/{flag=0} $0 == rep{getline;getline;flag++} flag' $file > $3
使用&gt; $ 3覆盖&gt;&gt; 3美元追加产出
<强>输出强>
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes
AWK解释
BEGIN{rep="report_id:"rep} #concat variable to report_id
flag && /^report_id/{flag=0} #reset print flag
$0 == rep{getline;getline;flag++} #check for match, if matched the skip to 2nd line and set print flag
flag #print the line
修改强>
RUN: ./ script.sh device
cat script.sh
#! /bin/bash
report=$1
FILE=report_type_id_list.yml
OUTPUT=report_type_id_copy_fields.sh
copy_fields()
{
awk -vrep="$report" 'BEGIN{rep="report_id:"rep ;} flag && /^report_id/{flag=0} $0 == rep{getline;getline;flag++} flag' $FILE > $OUTPUT
}
copy_fields
输出
cat report_type_id_copy_fields.sh
- date
- views
- comments
- shares
- channel_id
- watch_time_minutes