How do you parse a filename in bash?

天涯浪子 提交于 2019-11-27 02:32:02

问题


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.


回答1:


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




回答2:


A nice and elegant (in my mind :-) using only built-ins is to put it into an array

var='system-source-yyyymmdd.dat'
parts=(${var//-/ })

Then, you can find the parts in the array...

echo ${parts[0]}  ==> system
echo ${parts[1]}  ==> source
echo ${parts[2]}  ==> yyyymmdd.dat

Caveat: this will not work if the filename contains "strange" characters such as space, or, heaven forbids, quotes, backquotes...




回答3:


Depending on your needs, awk is more flexible than cut. A first teaser:

# echo "system-source-yyyymmdd.dat" \
    |awk -F- '{printf "System: %s\nSource: %s\nYear: %s\nMonth: %s\nDay: %s\n",
              $1,$2,substr($3,1,4),substr($3,5,2),substr($3,7,2)}'
System: system
Source: source
Year: yyyy
Month: mm
Day: dd

Problem is that describing awk as 'more flexible' is certainly like calling the iPhone an enhanced cell phone ;-)




回答4:


Use the cut command.

e.g.

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

will extract the first bit.

Change the value of the -f parameter to get the appropriate parts.

Here's a guide on the Cut command.




回答5:


Another method is to use the shell's internal parsing tools, which avoids the cost of creating child processes:

oIFS=$IFS
IFS=-
file="system-source-yyyymmdd.dat"
set $file
IFS=$oIFS
echo "Source is $2"



回答6:


The simplest (and IMO best way) to do this is simply to use read:

$ IFS=-. read system source date ext << EOF
> foo-bar-yyyymmdd.dat
> EOF
$ echo $system
foo
$ echo $source $date $ext
bar yyyymmdd dat

There are many variations on that theme, many of which are shell dependent:

bash$ IFS=-. read system source date ext <<< foo-bar-yyyymmdd.dat

echo "$name" | { IFS=-. read system source date ext
   echo In all shells, the variables are set here...; }
echo but only in some shells do they retain their value here


来源:https://stackoverflow.com/questions/49403/how-do-you-parse-a-filename-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!