What is the best way to do string manipulations in a shell script?

I have a path as a string in a shell script, can be absolute or relative:

/usr/userName/config.cfg

or

../config.cfg

I want to extract the file name (the part after the last /, so in this case: "config.cfg")

I find the best way to do this with a simple simple expression? It's right? Should I use sed or awk instead?

The string processing functions in shell scripts look pretty primitive in themselves and seem very esoteric.

Any sample solutions are also welcome.

+3
source share
4 answers

Instead of string manipulation, I just used

file=`basename "$filename"`

Edit

( , $filename):

file=$(basename $filename)
+6

bash, bash:

FILE="/path/to/file.example"
FILE_BASENAME="${FILE##*/}"

, , glob .

Double %% , .

, :

FILE=${FILE// /_}

, .

, .

+11

perl, .

, , - basename.

+1

sed , :

echo "/usr/userName/config.cfg" | sed -e 's+^.*/++'

:

>echo "/usr/userName/config.cfg" | sed -e 's+^.*/++'
config.cfg
+1

Source: https://habr.com/ru/post/1704659/


All Articles