2017-07-03 111 views
0

我有包含许多行的文件。每行有以下信息:使用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 
+0

checkout'while'用'IFS ='读取'bash'中的文件。它可能有帮助。 –

+0

**并将其分配给变量** - 用于什么? – RomanPerekhrest

+0

将其用作其他脚本的输入文件 – rehman

回答

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 

当这脚本运行,它显示以下内容:

[email protected]:/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 
... 
[email protected]:/tmp$ 

如某些注释中所述,请阅读有关read命令和cut(1)命令的内容。希望能帮助到你。

相关问题