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
Foody
  • 177
  • 1
  • 10
  • 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}')``` – Book Of Zeus Aug 23 '21 at 02:42
  • Also: `fileDate=$(echo "$file" | cut -d '_' -f1)` – LMC Aug 23 '21 at 02:50
  • 1
    `file='20210823_Club_Member_Name_by_ID.txt'; file_date="${file%%_*}"` – Jetchisel Aug 23 '21 at 03: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. – user1934428 Aug 23 '21 at 07:17

1 Answers1

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.

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38
  • 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.](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Aug 23 '21 at 13:14