Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to use regex in bash at line of variable assignment

e.g.

oldip="14\.130\.31\.172"
oldip_a="14.130.31.172" << How to use regex to del all '\'? and assign to oldip_a

Do you have any idea?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

To remove the \, use bash parameter substitution.
// means replace all ... (a single / would mean replace only the first)
//\\ means replace all \ (backslash) chars
/} means replace with nothing (There is nothing bewtween / and the closing }

ip="14\.130\.31\.172"
echo "${ip//\\/}"

Output

14.130.31.172

Or, if there are many occurrences \. to do, in a file with many such IP addresses, you can assign each modified value to an array item.

ip=($(printf '
172.31.130.14
14\.130\.31\.172
33\.135\.220\.0
' | sed 's/\\//g'))
for ((i=0;i<${#ip[@]};i++));do
  echo "${ip[i]}"
done

output

172.31.130.14
14.130.31.172
33.135.220.0

?! .. I just noticed that your second data item is a reversal of the first.. Is that what you want as your output? (probably not, but it got me wondering)..

share|improve this answer
    
How to use regex in echo? Are you can explain to me? –  asdf Mar 14 '12 at 6:20
    
cheers! that's a very nice answer. –  asdf Mar 14 '12 at 6:45
    
@Peter.O : can you please explain me what {#ip[@]} specifies? –  pradeepchhetri Mar 14 '12 at 7:25
    
Regarding the many case: “If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.” – man bash. ip=('172.31.130.14' '14\.130\.31\.172' '33\.135\.220\.0'); echo "${ip[@]//\\/}" –  manatwork Mar 14 '12 at 10:21
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.