Parameter expansion: is it possible to extract an internal substring?

For example, how can I extract just leafpad out of

/usr/share/applications/leafpad.desktop

I would like to account for not just /usr/share/applications/ but also for ~/.local/share/applications.

The best I could come up with is to use a combination:
echo ${selected##*/} | cut -d '.' -f1 (where selected is in the context of the code below)

#!/usr/bin/bash

desktop_file() {
  fd . -H -e .desktop /usr/share/applications "$HOME/.local/share/applications"
}

selected="$(desktop_file | sort | fzf --reverse)"
[ -z "$selected" ] && exit
cd || return
echo ${selected##*/} | cut -d '.' -f1 |  tr '[:upper:]' '[:lower:]' | xargs -I{} setsid -f bash -c "{}"

Source: bits taken from here

(The tr bit is because of Alacritty.)

basename /usr/share/applications/leafpad.desktop .desktop
#!/usr/bin/env bash

MYPATH=/usr/share/applications/leafpad.desktop
NAME=$(basename ${MYPATH} .desktop)
echo "$NAME"
1 Like

This won’t remove the .desktop suffix if I’m right

You are right, I didn’t read it carefully enough. Fixed.

Maybe first we need to know exactly what the OP wants to do…

1 Like

I’ve given the entire script. It’s an application launcher with .desktop files as the source.

Do you want to extract the app name from the name of the desktop file, or from the contents of the desktop file?

Just from the name of the .desktop file, not from the contents.

OK, then basename is your command.

1 Like

Be aware that desktop files can also look like this:

okularApplication_powerpoint_calligra.desktop
org.strawberrymusicplayer.strawberry.desktop

Yes! I have /usr/share/applications/org.pwmt.zathura.desktop and that’s a problem.

So back to the drawing board :sweat_smile:!

$ basename /usr/share/applications/org.pwmt.zathura.desktop .desktop
org.pwmt.zathura

Is this output not what you expect?

If you just want the name, I agree with @manual that extracting it out of the desktop file is a better solution.

deleted by author :blush:

Something like this:

cat /usr/share/applications/xed.desktop  | grep ^Exec= | head -n1 | cut -d'=' -f2 | awk '{print $1}'
1 Like

But even the above may not be optimal if there are many Exec= lines, or quotes used…

Yes, and there are the options like xed --new window and field codes (%F, %U, etc).

Overall too many possibilities :frowning:

The above already handles some problems, try it and see. :wink:

And I just saw there is
/usr/share/applications/org.gnome.FileRoller.desktop:TryExec=file-roller