Satya
Satya

Reputation: 87

check the output for Numeric and Alphabet using shell script

I have a file where i will have IP address and server FQDN names.

example file

192.168.1.1
192.168.2.1
kubuntu1.example.com
kubuntu2.example.com

i want to write a shell script where i want to get the output of ip address server name without domain name

if file has numeric don't do anything else if it has alphabet then get me the output like

192.168.1.1
192.168.2.1
kubuntu1
kubuntu2

Thanks in advance for the help.

New to shell script so not so sure on regular expressions thing.

Upvotes: 1

Views: 106

Answers (2)

hek2mgl
hek2mgl

Reputation: 158030

You can use sed. Like this:

sed 's/\([a-z][^.]*\).*/\1/' input.file

Explanation:

I'm using the s (substitute) command to "cut off" everything behind the first dot (including the dot) on lines starting with a lowercased letter:

s                      The substitute command
/\([a-z][^.]*\).*/     Search pattern
\1                     The replacement pattern.
/                      End of s command

The search pattern explained

/                      Starting Delimiter
\(                     Start of capturing group
[a-z]                  A lowercased character
[^.]*                  Zero or more non . characters
\)                     End of capturing group
.*                     Rest of the line
/                      Ending delimiter

The replacement pattern simply injects the content of the first capturing group \1.


Btw, if you aren't addicted to typing cryptic characters like me, you can pass the -r option to sed. Having this you'll usually save most escaping and the command looks cleaner:

sed -r 's/([a-z][^.]*).*/\1/' input.file

Usually domain names won't contain uppercased characters, but pigs can fly ... To get sure you'll capture domains starting with uppercased characters too you should change

[a-z]

to

[a-zA-Z]

Upvotes: 1

anubhava
anubhava

Reputation: 785266

You can use this awk command:

awk -F '\\.' '!($1+0){$0=$1} 1' file
192.168.1.1
192.168.2.1
kubuntu1
kubuntu2

Explanation:

-F '\\.'   # set input field separator as . (DOT)
!($1+0)    # check if first field is numerically equal to zero (to catch non numeric)
$0=$1      # if yes then set record = first file
1          # default awk action to print whole line

Upvotes: 1

Related Questions