I’m studying bash, and I came across this Stackoverflow thread which contains this bit of code:

var="abcde"
echo ${var%d*}

The output is abc, but I can’t figure out why. I understand that %d is used to indicate an integer number and * represents anything, but I can’t figure out why those together would truncate var to only 3 characters.

  • logging_strict@lemmy.ml
    link
    fedilink
    English
    arrow-up
    1
    ·
    edit-2
    13 hours ago

    already answered the question

    Would like to add, don’t do this or shoulda used Python.

    Manipulating strings in bash is a mistake and creates spaghetti code. This goes for sed and awk as well.

    Python equivalent

    str_x = "abcde"
    pos = str_x.index("d")
    ret = str_x[:pos]
    print(ret)
    

    In one line, capturing the output into a bash variable

    ret=$(python -c 'str_x = "abcde"; pos = str_x.index("d"); ret = str_x[:pos]; print(ret)')