this post was submitted on 07 Oct 2024
12 points (100.0% liked)

Bash

779 readers
1 users here now

Talk about the Bash Shell and Bash scripting

founded 4 years ago
MODERATORS
 

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.

top 6 comments
sorted by: hot top controversial new old
[–] beatnik86 19 points 2 months ago (1 children)

That's manipulation of the string held in var. Dollar sign and curly braces wrap the variable, the single percent sign say remove the shortest matching substring from the end of the variable contents, and the 'd*' is the substring to match, a lowercase d followed by any characters in this instance. var will still hold the entire original string, only the echo output is modified here. You can find more documentation here, https://tldp.org/LDP/abs/html/string-manipulation.html.

[–] SpaceNoodle 4 points 2 months ago

That's the exact Bible I would have linked to.

[–] [email protected] 2 points 1 month ago

You may be confusing that %d with printf syntax. I'm not entirely sure, but I think what the percent sign means is delete everything from the end of string until the first occurence of letter "d"

[–] [email protected] 0 points 2 weeks ago* (last edited 2 weeks ago) (1 children)

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)')

[–] [email protected] 1 points 1 week ago (1 children)

Thought this was a bash community

[–] [email protected] 1 points 1 week ago

it's a bash community as long as bash is the right tool for the job. For text manipulation, not so much. In Python can also do some really stupid things. Then will get advice. They'll say, just don't do that

Which is what i'm doing here.

just don't do that