hector lerma
hector lerma

Reputation: 31

Split lines in a file and compare with a hostname in perl

I got a file separated by ":"

uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
antbexw:x:59000:80::/usr/var/log:/bin/ksh

Each ":" is a separator, thus the aim is to extract position 0 and position 5 to have:

uucp /var/spool/uucp
operator /root
games /usr/games
antbexw /usr/var/log

Then only print line containing antbexw which is in fact the machine hostname.

I have achieved to read the file, split but not the compare against the machine hostname to only print out the antbexw line

antbexw /usr/var/log

Here my script, would you help me out to construct the Condition to print only the line I need? or to propose another method.

#!/usr/bin/perl -w
use strict;
use warnings;
use diagnostics;
use Sys::Hostname;
my $host = hostname;

print "$host\n";

open(my $fh, '<', 'file.txt') or die "cannot open < file.txt: $!";
while (my $line = <$fh>)
 {
my@fields = split(":",$line);
print "=*=*=*=*User=*=*=*=* \n$fields[0] \nDirectory $fields[5]\n";
}  

close($fh) || warn "close failed: $!";

Upvotes: 0

Views: 93

Answers (2)

hector lerma
hector lerma

Reputation: 31

in the mean time i did some other tries and got to this solution:

while (my $line = <$fh>)
{
if($line =~ m/$host/)
{
my@fields = split(":",$line);
print MYFILE"=*=*=*=*SftpUser=* \n$fields[0] \nDirectory $fields[5]\n"; 
}}

Upvotes: 0

choroba
choroba

Reputation: 241938

To compare strings, use the eq operator:

if ($fields[0] eq $host) {
    print "=== User ===\n$fields[0]\nDirectory $fields[5]\n";
}

Some unrelated details:

You already have use warnings, no need to specify -w on the shebang line.

The first argument to split is a regex (or a space), so it's better not to use strings.

Your code would be more readable if you indented properly and added some whitespace around punctuation (after commas, before @).

Upvotes: 2

Related Questions