1

I assume that there may be a better way to do it but the only one I came up with was using AWK.

I have a file with name convention like following:

testfile_2016_03_01.txt

Using one command I am trying to shift it by one day testfile_20160229.txt

I started from using:

file=testfile_2016_03_01.txt
IFS="_"
arr=($file)
datepart=$(echo ${arr[1]}-${arr[2]}-${arr[3]} | sed 's/.txt//')
date -d "$datepart - 1 days" +%Y%m%d

the above works fine, but I really wanted to do it in AWK. The only thing I found was how to use "date" inside AWK

new_name=$(echo ${file##.*} | awk -F'_' ' {
"date '+%Y%m%d'" | getline date;
print date
}')
echo $new_name

okay so two things happen here. For some reason $4 also contains .txt even though I removed it(?) ##.*

And the main problem is I don't know how to pass the variables to that date, the below doesn't work

`awk -F'_' '{"date '-d "2016-01-01"' '+%Y%m%d'" | getline date; print date}')

ideally I want 2016-01-01 to be variables coming from the file name $2-$3-$4 and substract 1 day but I think I'm getting way too many single and double quotes here and my brain is losing..

4
  • 1
    Remove from end: ${file%%.*} instead of ## (or just one % as there is just one . anyway). Commented Mar 4, 2016 at 21:55
  • 1
    Do you have or can you get GNU awk? Commented Mar 4, 2016 at 21:59
  • Thanks BenjaminW, it works (though I don't know why ## didn't, I do have it in different scripts). @EdMorton I do have gawk yes Commented Mar 4, 2016 at 22:03
  • ## removes matching from the start, you'd use it to get, e.g., an extension or basename: var='/abc/def/file.txt'; echo "${var#*.}"; echo "${var##*/}" returns txt and file.txt. Commented Mar 4, 2016 at 22:51

3 Answers 3

2

Equivalent awk command:

file='testfile_2016_03_01.txt'
echo "${file%.*}" |
awk -F_ '{cmd="date -d \"" $2"-"$3"-"$4 " -1 days\"" " +%Y%m%d";
          cmd | getline date; close(cmd); print date}'

20160229
Sign up to request clarification or add additional context in comments.

1 Comment

Worked as a charm. Thanks
1

WIth GNU awk for time functions:

$ file=testfile_2016_03_01.txt
$ awk -v file="$file" 'BEGIN{ split(file,d,/[_.]/); print strftime(d[1]"_%Y%m%d."d[5],mktime(d[2]" "d[3]" "d[4]" 12 00 00")-(24*60*60)) }'
testfile_20160229.txt

Comments

0

This might work for you:

file='testfile_2016_03_01.txt'
IFS='_.' read -ra a <<< "$file"
date -d "${a[1]}${a[2]}${a[3]} -1 day" "+${a[0]}_%Y%m%d.${a[4]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.