Reputation: 55
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!
Upvotes: 2
Views: 2726
Reputation: 784938
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
Upvotes: 1
Reputation: 3289
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
Upvotes: 0
Reputation: 414149
To get the name of the shell or shell script from inside .hidden_file.sh
you could use $0
:
echo "$0"
Upvotes: 0