kibe
kibe

Reputation: 181

How to trim a string in shell script with a specific pattern?

How's everyone doing?

So, if I run xdotool getactivewindow getwindowname, it gives the full title of the current window, for example:

fish home/kibe/Documents — Konsole

Blablablabla - Stack Overflow - Google Chrome

The thing is, I only want the application name (Konsole and Google Chrome).

I can easily do it in Python, as such:

def getAppTitle (fullStr):
    lastDashIndex = None
    for i in range(len(fullStr)):
        if fullStr[i] == '-' or fullStr[i] == '—':
            lastDashIndex = i
    return fullStr[lastDashIndex+2:] if lastDashIndex else fullStr

print(getAppTitle('blablabla - blablabla - ApplicationName'))
# returns ApplicationName

I have been trying to do the same in shell script but I can't do it for the life of me. Also, for some reasons, some applications use "-" (normal dash) and others "—" (em dash).

How can I do that in shell?

Upvotes: 0

Views: 102

Answers (1)

thanasisp
thanasisp

Reputation: 5975

You have to use this 'em dash' or dash as the field separator and print the last field:

xdotool getactivewindow getwindowname | awk -F"—|-" '{print $NF}'

I am not sure where this 'em dash' comes from, I had to copy paste it for the above command.


Maybe better, use two characters as the FS, any dash and a space, to get the same as your script, with the space trimmed.

xdotool getactivewindow getwindowname | awk -F"— |- " '{print $NF}'

Upvotes: 3

Related Questions