Linux 在bash中搜索文本中的日期并将其放入变量数组中

Linux 在bash中搜索文本中的日期并将其放入变量数组中,linux,bash,Linux,Bash,我有一个包含以下行的txt文件: 2017-06-15 Take the car for inspection to change the wheels.mkd 2018-03-17 Crear un entorno virtual con Docker y xfce.mkd 2018-02-25 Envíar vídeo de explicación de configuración email de tunegocioenlanube a María.mkd 2018-03-08 crear

我有一个包含以下行的txt文件:

2017-06-15 Take the car for inspection to change the wheels.mkd
2018-03-17 Crear un entorno virtual con Docker y xfce.mkd
2018-02-25 Envíar vídeo de explicación de configuración email de tunegocioenlanube a María.mkd
2018-03-08 crear curso tu formula emocional +tunegocio.mkd
我想在年、月、日中加入一系列bash:

year=( "2017","2018" )
month=( "03","06","02" )
day=( "08","15","17","25" )

谢谢大家。

您可以使用正则表达式来解决这个问题。请参见
awk
sed

但是,如果regex对您来说非常复杂,您可以使用
cut
命令用一个更简单的表单来解决这个问题

cut
是一个命令,允许获取行的特定部分(类似于其他语言中的split)

您只需使用-d选项设置分隔符,并使用-f选择字段

在您的情况下,您可以在文件的每一行中使用:

date=$(echo $line | cut -d " " -f 1)
year=$(echo $date | cut -d "-" -f 1)
month=$(echo $date | cut -d "-" -f 2)
day=$(echo $date | cut -d "-" -f 3)
有了它,您可以获得所需的字段。然后,您可以将其保存在数组或任何需要的地方

要将元素添加到现有数组,可以阅读以下文章:

要逐行读取文件,请执行以下操作:

如果顺序不重要,您可以使用以下内容:

#!/bin/bash

declare -A years months days # declare associative arrays

while read -r date file; do
    IFS=- read -r year month day <<<"$date" # split date on -

    # set keys in associative arrays
    years[$year]=  
    months[$month]=
    days[$day]=
done < file

# use keys to make arrays of values
year=( "${!years[@]}" )
month=( "${!months[@]}" )
day=( "${!days[@]}" )
#/bin/bash
declare-A年月日#声明关联数组
读取-r日期文件时;做
如果s=-read-r年-月-日您可以执行以下操作:

year=($(grep -Po '^\d+[^-]' InputFile.txt | uniq))
month=($(grep -Po '(?<=-)[0-9]+(?=-)' InputFile.txt | sort -u))
day=($(grep -Po '(?<=-)[0-9]+(?= )' InputFile.txt) | sort -u))
year=($(grep -Po '^\d+[^-]' InputFile.txt | uniq))
month=($(grep -Po '(?<=-)[0-9]+(?=-)' InputFile.txt | sort -u))
day=($(grep -Po '(?<=-)[0-9]+(?= )' InputFile.txt) | sort -u))
08 15 17 25
while read Line
     do
         echo $Line
         var1=`echo "$Line" | awk 'BEGIN{FS=" "} {print $1}' | awk 'BEGIN{FS="-"} {print $1}'`
         var2=`echo "$Line" | awk 'BEGIN{FS=" "} {print $1}' | awk 'BEGIN{FS="-"} {print $2}'`
         var3=`echo "$Line" | awk 'BEGIN{FS=" "} {print $1}' | awk 'BEGIN{FS="-"} {print $3}'`
         year+=("$var1")
     month+=("$var2")
     day+=("$var3")
done < array.txt
printf '%s\n' "${year[@]}"
printf '%s\n' "${month[@]}"
printf '%s\n' "${day[@]}"