使用shell脚本提取每一行并将其分配给变量并将其单独保存为新文件

时间:2017-07-03 05:31:32

标签: shell

我的文件包含很多行。每行包含以下信息:

xxxxx,2017-06-26 13:12:53.750,-9.5949,124.6654,23.29,xxxx,yyyyy,mb,5.0,

xxxxx,2017-06-24 07:27:07.700,-41.2392,80.6425,10.0,xxxx,yyyyy,mb,5.2,

xxxxx,2017-06-24 02:37:18.140,-19.4438,34.509,24.44,xxxx,yyyyy,Mww,5.6,

我想使用shell脚本提取每一行并将其分配给变量并将其单独保存为新文件。输出文件的内容应如下所示:

YEAR=2017

MONTH=06

DAY=26

HOURS=13

MIN=12

SEC=53

MSEC=750

LAT=-09.5949

LONG=124.6654

DEP=23.29

MAG=5.0

1 个答案:

答案 0 :(得分:0)

这个脚本是一个读取和解析文件的例子(我称之为数据文件" data.txt"):

#!/bin/sh

IFS=,

# read lines like: xxxxx,2017-06-26 13:12:53.750,-9.5949,124.6654,23.29,xxxx,yyyyy,mb,5.0,
while read xxx1 datetime lat long dep xxx2 xxx3 xxx4 mag; do

  # input lines are partly split
  echo "Read $datetime"
  echo "lat=$lat long=$long dep=$dep"

  # parse datetime field which is like 2017-06-26 13:12:53.750
  date=$(echo $datetime |cut -d" " -f1)  # -d tells the field separator
  time=$(echo $datetime |cut -d" " -f2)  # -f tells the field number to extract
  echo "date=$date time=$time"

  # extract year value from date, which is like 2017-06-26
  year=$(echo $date |cut -d"-" -f1)

  echo "year=$year"

  # go on this way to fill up all the variables...
  # ...left as an exercize...!

  # after this comment, down until the "done" keyword,...
  # ...you will have all the variables set, ready to be processed

done <data.txt

运行此脚本时,它显示以下内容:

user@machine:/tmp$ ./script.sh
Read 2017-06-26 13:12:53.750
lat=-9.5949 long=124.6654 dep=23.29
date=2017-06-26 time=13:12:53.750
year=2017
Read 2017-06-24 07:27:07.700
...
user@machine:/tmp$

如某些评论中所述,请阅读有关read命令和cut(1)命令的信息。希望它有所帮助。