0

I have a file 20210823_Club_Member_Name_by_ID.txt. I want to get only the first element of the file name which is 20210823 and store it into a variable using shell script.

Currently, my code can print out the first element in the terminal but I also want to store it into a variable for further usage.

file='20210823_Club_Member_Name_by_ID.txt'
echo "$file" | awk -F'[_.]' '{print $1}'


// I try to store it like below, but it does not work

fileDate= echo "$file" | awk -F'[_.]' '{print $1}'
echo $fileDate
4
  • you where close, you need to "execute" the "echo "$file" as part of a command by using $() eg:fileDate=$(echo "$file" | awk -F'[_.]' '{print $1}') Commented Aug 23, 2021 at 2:42
  • Also: fileDate=$(echo "$file" | cut -d '_' -f1) Commented Aug 23, 2021 at 2:50
  • 1
    file='20210823_Club_Member_Name_by_ID.txt'; file_date="${file%%_*}" Commented Aug 23, 2021 at 3:22
  • @Foody : Your attempt just sets the environment variable fileDate to the empty string and run in this context the echo command. Actually, the comment given by Jetchisel provides IMO the most natural solution to this task. Commented Aug 23, 2021 at 7:17

1 Answer 1

0

As Jetchisel commented, you can use shell parameter expansion to safely extract the value. The %% operator removes as much of the matching text as possible, starting from the end of the string; if we use _* then this will essentially remove everything after and including the first underscore.

file='20210823_Club_Member_Name_by_ID.txt'
fileDate="${file%%_*}"

The fileDate variable will now contain 20210823.

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

1 Comment

You could also use the pattern ${file%%[._]*} to precisely implement the OP's Awk code. Don't forget to quote the variable when you use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.