ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I'm trying to use the bash "parameter extension" mechanism to extract a substring which matches a certain pattern from a string.
So far I'm succesfully using the following in a bash script:
Code:
test='this is my example video with a resolution of 400x500 pixel.'
echo ${test//???x???/}
This will remove the '400x500' substring from the test string and output the rest.
What I want to achieve is exactly the opposite: I want to remove everything _except_ the '400x500' substring, thus using regular expressions to extract a specific substring from a string in a bash script.
Is such a "negation" possible in the above script fragment? Is there a better way to extract a substring which matches a specific regex pattern from a string in bash?
Anyway, doing it "pure bash" is possible. But a bit more work.
Code:
test='this is my example video with a resolution of 400x500 pixel.'
head=${test%%x[0-9]*}
tail=${test##*[0-9]x}
X_res=${head##* }
Y_res=${tail%% *}
res_string=${X_res}x${Y_res}
echo $res_string
Firstly, DaneelGiskard, your script doesn't work. It doesn't only strip out the '400x500' substring, it strips out any 'x' and the 3 characters either side of it. It should be something like:
Code:
echo ${test//[0-9][0-9][0-9]x[0-9][0-9][0-9]/}
I agree with Hko, string manipulation easily becomes over-complicated in bash, it's better to use tools that are designed for the job. Here's the simplest version I could come up with using pure bash:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.