简体   繁体   中英

regex for getting path and filename from string in linux

In bash I would like to get filename from a command line string. But not the current ($0) script!

I have a file full of scripts with parameters. I need just the scripts from it!

For example i have a string like: /path/to/file parameter1 -p2

i would like to get: /path/to/file (without the parameters) even in cases:

/an\ example/with.dot.in_it/.hidden_file.sh par\ ameter1 p.dot.2
./script.sh p1 p2
../script.sh p1 p2
/any////relative/../path/./to/script.sh p1 p2

So in any valid linux path and filename cases!

Is there a regex for this purpose, or is there any other way to get this?

Thanks in advance!

You can use perl's command line regex feature combined with readlink command to always get full path to your script. Let's data is your file name with all the command and their parameters. You can use script like this to get full path of your scripts:

while read -r F
do
    SCRIPT=$(perl -pe 's/^(.*?)(?<!\\) .*$/\1/;s/\\//g' <<< $F)
    readlink -f "$SCRIPT"
done < data

要从.hidden_file.sh内部.hidden_file.sh shell或shell脚本的名称,可以使用$0

echo "$0"

您可以使用dirname命令。

if you really want to use regular expressions (many better solutions were discribed above) then this might help you:

/^(.+[^\\]) /

this matches all characters up to the first space, which doesn't follow a \\

you get the path from the captured group

basename "$string"

要么

${string##*/}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM