MTALY
MTALY

Reputation: 1782

How to remove initial and final digits from strings using bash scripting

Quite new to bash scripting so If I have a list usually text files each file specific for one country for example USA.txt client addresses with leading ZIP and ending P.O Box (Numbers are masked for privacy) :

38495newyork940
454354irvine40404
2333wathington4440
32333california002929
23234dallas4th93303 

I want to run USA.txt as an argument to a bash script that would remove the leading and final digits from each line. Please note that certain cities or states might have numbers within the names so I want to keep them.

I tried to run it against sed commands but I can't combine the end result I just remove the leading or final numbers with commands like :

for leading digits:

sed -r 's/^[0-9]+(.*[^0-9].*)$/\1/g'

and for ending digits:

sed "s/\([^0-9]\)[0-9]*\s*$/\1/"

I need the output like:

newyork
irvine
wathington
california
dallas4th

Thanks

Upvotes: 1

Views: 64

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65851

You can give sed as many commands as you like:

$ sed 's/^[0-9]*//; s/[0-9]*$//' USA.txt 
newyork
irvine
wathington
california
dallas4th

Or you can do it all in one command:

$ sed 's/^[0-9]*\(.*[^0-9]\)[0-9]*$/\1/' USA.txt 
newyork
irvine
wathington
california
dallas4th

Upvotes: 3

Related Questions