Friday, January 23, 2015

small ruby scripts,useful or practical?

#!/usr/bin/env ruby
#moving files *php*.pdf
d="/home/whatsup/Desktop/book2/"
de="/home/whatsup/Desktop/book2/php/"
system("find #{d} -name \"*.pdf\" | grep -i \"php\" > /tmp/phpbook")
a=File.readlines("/tmp/phpbook").each { |b| system("mv -vf  \"#{b.strip}\" #{de}")}
~   



#!/usr/bin/env ruby
#suming of uid
P="/etc/passwd"
i=0
sum_uid=0
a=File.readlines(P)
while i < a.size
  # Getting array for each users
  getuid=a[i].split(/:/)
  # Getting uid for each users
  uid=getuid[2]
  # Getting user for each users
  user=getuid[0]
  # summing uids. Should convert to integer
  sum_uid+=uid.to_i
  i += 1
end

  puts "sum of uid = #{sum_uid}"

#!/usr/bin/env ruby
#suming of uid
sum=0
File.readlines("/etc/passwd").collect {|line| sum += line.split(/:/)[2].to_i}
puts "The sum of uid is #{sum}"

#Using bash shell(gawk study)
#!/usr/bin/env bash
#Getting sum of uid on /etc/passwd file using awk(gawk)
#GNU Awk 4.0.1

TEMP_FILE="/tmp/uid"
AWK=$(which awk)
PASSFILE="/etc/passwd"

#Getting uid via awk ':' FS
$AWK -F: '{print $3}' $PASSFILE > $TEMP_FILE

#Using awk(gawk)
$AWK 'BEGIN{FS="\n"; RS=""} {
 total = 0
 i = 1
 while (i <= NF)
 {
    total += $i
    i++
    print "Current total is=" total
    print "It will increase by " $i
}

  print "Total_Sum_of_uid_of_passwd file:", total
  print "NF="NF
}' $TEMP_FILE


#Removing TEMP_FILE
rm -f $TEMP_FILE



#!/usr/bin/env ruby
# Sorting by uid.
# puts File.readlines("/etc/passwd").compact.sort_by {|line| line.split(/:/)[2].to_i}
# Just above line is simpler and I think it is better maybe.
p="/etc/passwd"
i=0
sort_by_uid=[]
p_array=File.readlines(p)
while i < p_array.size
  # Getting array for each users
  get_each=p_array[i].split(/:/)
  # Getting uid for each users
  uid=get_each[2]
  # Getting user for each users
  rest = get_each[0]+":"+get_each[1]+":"+get_each[2]+":"+get_each[3]+":"+get_each[4]+":"+get_each[5]+":"+get_each[6]
  sort_by_uid << uid +":"+ rest
  i += 1
end


  # to sort must convert to to_i integer
  sort_by_uid=sort_by_uid.sort_by { |k,s| k.to_i }
  puts "Soting passwd file by uid number"
  puts sort_by_uid



No comments:

Post a Comment