【问题标题】:Extract each line using shell script and assign it to variables and save it individually as new file使用 shell 脚本提取每一行并将其分配给变量并将其单独保存为新文件
【发布时间】:2017-07-03 05:31:32
【问题描述】:

我的文件包含多行。每一行都有以下信息:

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

【问题讨论】:

  • IFS=, 签出while read 中的文件bash。它可能会有所帮助。
  • 并将其分配给变量 - 为什么?
  • 将其用作其他脚本的输入文件

标签: shell


【解决方案1】:

此脚本是读取和解析文件的示例(我将数据文件称为“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) 命令的信息。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2011-06-26
    • 2018-08-22
    • 2021-02-13
    • 1970-01-01
    • 2017-11-02
    • 2019-05-24
    • 2014-05-13
    相关资源
    最近更新 更多