简体   繁体   中英

Extract date from the end of filename in linux

I'm working with a shell program and have some files with these patterns:

abc_def_ghjuy_2017-09-12_15-30-40.txt
abc_def_khujdr_bv_bmg_2017-09-12_15-31-40.txt
abc_def_pkiljoy_vcdfr_2017-09-12_15-32-40.txt
abc_def_charidp_bf_mj_fr_2017-09-12_15-32-40.txt

How can I extract date that is in position 2 of the filename before period and save it in a variable?

You can use this simple script. In find.sh

#!/bin/bash
ls abc_def_*-* | sed 's/abc_def\(.*\)\.txt/\1/' >> file
sed -r 's/.*(.{8})/\1/' file >> file5
mapfile -t array < file5
sudo rm -r file

Run this script bash.sh . Now your desired fields are placed as variables.

$ echo "${array[1]}"
$ echo "${array[2]}"
$ echo "${array[3]}"
....

see the outputs If you get any better solution then let me know...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM