Anirudh S
Anirudh S

Reputation: 31

Extracting Timestamp part from a filename in shell

I have a filename like SID_Statistics_20191127.xlsx.I have to extract only the timepart from the file in a shell.The timepart may be changing but the format remains the same

Upvotes: 0

Views: 600

Answers (2)

Priya Agarwal
Priya Agarwal

Reputation: 512

As per your question description, if the format of the file remains the same and only timestamp part is changing then you can try the following code:

for file in *.xlsx
do
a=`echo $file|cut -d"_" -f3|cut -d"." -f1`
echo "$a"
done

Backticks in third line of code(a=echo $file|cut -d"_" -f3|cut -d"." -f1) is for execution of the code written inside the back-ticks.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133780

Could you please try following.

for file in *.xlsx; do val="${file##*_}";echo "${val%.*}"; done

OR a non-one liner form of solution is:

for file in *.xlsx
do
  val="${file##*_}"
  echo "${val%.*}"
done

Above will traverse through all .xslx files and will print the timestamp. Please refer https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html link for more details on parameter expansion as per @user1934428's comment.

Explanation: Adding a detailed level of explanation for above code:

for file in *.xlsx          ##Starting for loop which will traverse through all xlxs format files.
do
  val="${file##*_}"         ##Creating a variable val whose value will be 20191127.xlsx, what it does is, it substitutes everything till _ last occurrence with NULL.
  echo "${val%.*}"          ##Doing substitution from DOT to till end of variable val value with NULL and printing which will print timestamp as per OP need.
done                        ##Closing this specific program for loop here.

Upvotes: 1

Related Questions