-2

I have a log file that contains several lines, each with an IP, username, and URL. I need to create something that will take each IP in the line and, if starting with a 10 will append the word "ON" to the end of the line containing it. All other lines with any other IP not starting with a 10 will need to have the word "OFF" appended to it.

Example of log file:

10.10.10.10 jsmith1234 [URL] 
173.10.10.10 jsmith1234 [URL]

Example of what I want:

10.10.10.10 jsmith1234 [URL] ON
173.10.10.10 jsmith1234 [URL] OFF

I believe an if, then, else statement would work (used in a bash shell script), but I am very new to these and not sure where to start.

  • 2
    You should start with reading the manual for the shell or scripting language you want to use and then try things out. Then when you have concrete problems, come back here, post the program you got and any error messages. – Anthon Jun 10 '16 at 13:27
  • I believe that awk or sed is what you want. What have you tried so far? – MatthewRock Jun 10 '16 at 13:29
  • 1
    @MatthewRock, thank you so much! I was making this a LOT harder than it needed to be. I got my command to work. sed '/^10.*:/ s/$/ ON/' test_file.txt Sometimes the best help is just to be pointed to the right place. I appreciate you being helpful rather than rude. – sudo_maas Jun 10 '16 at 13:50
  • @sudo_maas Do you have any scripting language in mind? There are dozens of ways to do what you need. E.g. bash, sed, perl, awk, python, etc etc. – andcoz Jun 10 '16 at 13:51
  • @andcoz I apologize for being so unclear. I was wanting to use bash; and thanks to the help on here I now know how to make it work with sed as well. – sudo_maas Jun 10 '16 at 13:55
1

Did you try something? short example:

while read line; do
    if [[ $line = \10.* ]] ; then
        echo "$line ON"
    else
        echo "$line OFF"
    fi
done

As a result:

user@:~$ cat testo.txt 
10.10.10.10 jsmith1234 [URL] 
173.10.10.10 jsmith1234 [URL]

user@:~$ bash testo.sh < testo.txt 
10.10.10.10 jsmith1234 [URL] ON
173.10.10.10 jsmith1234 [URL] OFF
  • Thank you so much! I really appreciate you taking the time to help. I now know two ways I can make this work! – sudo_maas Jun 10 '16 at 13:53
1

I've solved the problem myself using the following solution:

sed '/^10.*:/ s/$/ ON/' test_file.txt

sed '/^10.*:/ s/$/ OFF/' test_file.txt
  • you missed "!", should be - "sed '/^10.*:/! s/$/ OFF/' test_file.txt" – malyy Jun 10 '16 at 15:31
-1
cat logfile | while read line
do
  echo ${line} | grep ^"10\." >/dev/null; r=${?}
  if [ ${r} -eq 0 ]
  then
    line=${line}" ON"
  else
    line=${line}" OFF"
  fi
echo ${line}
done > new_logfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.