1

just wondering if anyone could help me. I have a file containing a line:

W32i   APP   -     8.0.0.xxxxx shp 6SFE25~1.EXE

xxxxx are 5 digit numbers and the numbers are different for everytime. I want to be able to search for xxxxx and put it in a variable, so I can use this varibale. Do I use grep and sed?

3 Answers 3

1

a.txt

W32i   APP   -     8.0.0.xxxxx shp 6SFE25~1.EXE

code

 num=$(< a.txt)
 num=${num#*.0.0.}  # "left" remove everything up to .0.0.
 num=${num%% *}     # "right" remove "all" after " " char
 echo "num=${num}"

output xxxxx

You'll be glad that you spend time to understand the difference in how variable modifiers like ${num#xxx}, ${num##xx}, ${num%x}, ${num%%x} work. Advanced shells also support sed like substitutions, ${num/0/9} and ${num//0/9}.

IHTH

Sign up to request clarification or add additional context in comments.

3 Comments

It works! The comment really helps me learn, thank you so much! :)
To see the difference between the % and %% modifier, this code is a good example, i.e. only using % results in xxxxx shp, because the deletion starts at the right, finds the first ' ', and deletes to the end. With %%, the deleteion starts at the right, but then looks for all ' ' (moving to the right), and then deletes everything to the right, leaving only xxxxx. Good luck to all.
I was about to ask you the differences, and you've just explained it! Thank you so much for your detailed explaination. This is a great help for newbies like me :) xxx
1
#!/bin/sh

read < a.txt
[[ $REPLY =~ 8.0.0.([^\ ]*) ]]
echo ${BASH_REMATCH[1]}

output

xxxxx

Comments

1
perl -lne 'm/(\d{5})/g;print $1'

tested here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.