Register
It is currently Mon Sep 22, 2014 12:11 am

Even numbers from text file


All times are UTC - 6 hours


Post new topic Reply to topic  [ 5 posts ] 
Author Message
 PostPosted: Tue Jan 05, 2010 2:27 pm   

Joined: Tue Jan 05, 2010 2:26 pm
Posts: 2
Hello maybe someone could write bash script which from .txt text find even numbers and echo them?

Thank You.


Top
 Profile  
 PostPosted: Tue Jan 05, 2010 11:56 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 548
Hi Hexes,

What would look this .txt like?


Top
 Profile  
 PostPosted: Wed Jan 06, 2010 8:15 am   

Joined: Tue Jan 05, 2010 2:26 pm
Posts: 2
For example text1.txt is ->
Code:
Bash 2 4 3 1 scrpting 4 5 3 6 is 4 1 3 good thing 2 3


so on screen it prints
Code:
2 4 4 6 4 2

only even numbers of the text.


Top
 Profile  
 PostPosted: Wed Jan 06, 2010 9:20 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 548
Code:
#!/bin/bash

while read line; do
   for item in $line; do
      [[ $item = [0-9]* ]] && [ $((item % 2)) -eq 0 ] && echo -n "$item "
   done
   echo
done < infile


Top
 Profile  
 PostPosted: Wed Jun 22, 2011 4:14 pm   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
bash(1) version:

Code:
#!/bin/bash

if (($# != 1)) || [[ ! -f $1 ]]; then
    printf 'usage: %s <filename>\n' "${0##*/}" >&2
    exit 1
fi

while read -rd ' '; do
    if [[ $REPLY = [[:digit:]] ]] && ! ((REPLY & 1)); then
        printf '%d ' $REPLY
    fi 
done < "$1"

printf '\n'


awk(1) version:

Code:
#!/usr/bin/awk -f

{
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^[[:digit:]]+$/ && !($i % 2))
            printf("%d ", $i)
    }   
}

END \
{
    printf("\n")
}


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 5 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP