0

I've a file named 62810501601420200502.swt1 and in the end I have date in this format 20200502 and in front of it is just a random number which changes (dynamic). What I want is that I want to read only the date of the file and create log out of it through a shell script.

For example if today is 20200502 then I create log which says File found in the server, else if the file is not found then it simply says file not found on the server.

In the below code I have a file with a fixed name in front so I was able to create logs and other stuff.

But now my file name can be changed but date position is fixed and also the filename length is fixed.

#!/bin/sh

###############################################

PU=$(date +%d-%m-%Y)
Date=$(date +%Y-%m-%d)

###############################################


urban="/Path/of/file/PAYMENT_$PU.csv"

###############################################

if [ -f "$urban" ]; then 
echo "[$PU]  $urban file exist" >> /Mail_Scripts/mail.log
else
echo "[$Date]  $urban file does not exist" >> /Scripts/mail.log
echo "$Date,CCB,PAYMENT_$PU.csv,IP" >> /Scripts/iles.csv

fi
###############################################

Any suggestions or solution?

4
  • Welcome! You talk about a file .swt1 but then in your code the file is .csv. May 2, 2020 at 18:17
  • The description does not have much to do with the code in general as date +%Y-%m-%d does not output something like 20200502. PAYMENT_ is not a random number. May 2, 2020 at 18:31
  • @schrodigerscatcuriosity i'm using a different file now and i used to read csv from that script
    – Tim drake
    May 2, 2020 at 18:34
  • @HaukeLaging I used the given shell script as a reference what i've been using till now
    – Tim drake
    May 2, 2020 at 18:35

1 Answer 1

0

bash

If you use bash (the shebang line calls sh but the question is tagged with bash) then you can get the eight characters before the dot with this code:

var=62810501601420200502.swt1
tmp="${var%.*}"
date_string="${tmp: -8}"

sed

With sh you can use sed:

date_string="$(printf %s "$var" | sed -r 's/^(.*)(.{8})\..*$/\2/')"

grep

Or with grep:

date_string="$(printf %s "$var" | grep -oP '.{8}(?=\.)')"
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .