2

I have a requirement of extracting the 2nd, 3rd and 4th field from a file aaa.log and producing output as

- sqlplus -sl dbsnmp/Or8cle@\"COL3:COL4/COL2\" 

Input:

$ cat aaa.log aaa:fDb:a0081:1800:f1:dsds aaa:iDb:a0081:1801:i1:dsds aaa:pDb:a0081:1802:p1:dsds 

Expected Output:

sqlplus -sl dbsnmp/Or8cle@\"a0081:1800/fDb\" sqlplus -sl dbsnmp/Or8cle@\"a0081:1801/iDb\" sqlplus -sl dbsnmp/Or8cle@\"a0081:1802/pDb\" 

I extracted COL2 into a file:

$ cat aaa.log | cut -d":" -f2 > aaa_i.log $ cat aaa_i.log fDb iDb pDb 

and extracted COL3 and COL4:

$ cat aaa.log | awk -F: '{print $3 ":" $4}' > aaa_h_p.log $ cat aaa_h_p.log a0081:1800 a0081:1801 a0081:1802 

I tried using the below code.

 set -f IFS=' > ' set -- $( cat aaa_i.log) for i in `cat aaa_h_p.log` do printf "%s %s\n" "sqlplus -sl sys/hSys10Nov@\""${i}"/"$1"\"" done 

Current Ouput:

sqlplus -sl dbsnmp/Or8cle@\"a0081:1800/fDb\" sqlplus -sl dbsnmp/Or8cle@\"a0081:1801/fDb\" sqlplus -sl dbsnmp/Or8cle@\"a0081:1802/fDb\" 

I am getting only fDb in COL2 in the o/p, whereas I want all the values there. Please help me correct the code. Even changes using AWK are welcome.

4
  • Bash only supports one variable in a for loop; zsh supports at least two, if not more. (I've never needed to use more than two.)CommentedOct 27, 2016 at 16:40
  • 1
    Also backticks (e.g. `) are discouraged: use $(...) instead. see: Bash Hackers for more information.CommentedOct 27, 2016 at 16:42
  • Any other loop that could help the purpose or AWK utility ?CommentedOct 27, 2016 at 16:44
  • awk is more than powerful enough to do what I think you're trying to do, and I'm pretty sure it supports multiple variables in its loops. Try something like echo aaa:fDb:a0081:1800:f1:dsds | awk -F ':' '{printf("%s\n", "sqlplus -sl dbsnmp/Or8cle@\"$3:$4/$2\""); }'CommentedOct 27, 2016 at 16:47

3 Answers 3

4
while IFS=: read a b c d e f;do echo sqlplus -sl dbsnmp/Or8cle@\"$c:$d/$b\" done < aaa.log 
0
    0

    Arrays are nice for this kind of thing (especially if you're not sure how many fields there are):

    while IFS=: read -a var; do printf 'sqlplus -s1 dbsnmp/Or8cle@\\"%s:%s/%s\\"\n' "${var[2]}" "${var[3]}" "${var[1]}" done < aaa.log sqlplus -s1 dbsnmp/Or8cle@\"a0081:1800/fDb\" sqlplus -s1 dbsnmp/Or8cle@\"a0081:1801/iDb\" sqlplus -s1 dbsnmp/Or8cle@\"a0081:1802/pDb\" 
    0
      0

      Try below awk solution -

      vipin@kali:~$ awk 'BEGIN{FS=":"}{print v1$3,$4v2$2v3}' v1='sqlplus -sl dbsnmp/Or8cle@\\"' v2='/' v3='\\"' OFS=":" kk.txt sqlplus -sl dbsnmp/Or8cle@\"a0081:1800/fDb\" sqlplus -sl dbsnmp/Or8cle@\"a0081:1801/iDb\" sqlplus -sl dbsnmp/Or8cle@\"a0081:1802/pDb\" 

      FS,OFS = field seperators. v1,v2,v3 = variables to print sentences as per our requirement.

        You must log in to answer this question.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.