Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you parse a filename in bash?

I have a filename in a format like:

system-source-yyyymmdd.dat

I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter.

like image 579
Nick Pierpoint Avatar asked Sep 08 '08 10:09

Nick Pierpoint


People also ask

How do you read a filename in Unix shell script?

`basename` command is used to read the file name without extension from a directory or file path. Here, NAME can contain the filename or filename with full path. SUFFIX is optional and it contains the file extension part that the user wants to remove. `basename` command has some options which are described below.

What is $$ and $# in shell scripting?

So basically, $# is a number of arguments given when your script was executed. $* is a string containing all arguments. For example, $1 is the first argument and so on. This is useful, if you want to access a specific argument in your script.


1 Answers

You can use the cut command to get at each of the 3 'fields', e.g.:

$ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2 source 

"-d" specifies the delimiter, "-f" specifies the number of the field you require

like image 81
Bobby Jack Avatar answered Sep 29 '22 10:09

Bobby Jack