Results 1 to 5 of 5
  1. #1
    Join Date
    Nov 2011
    Posts
    5

    reading file in unix

    In a file (testfile.lst) I have the contents as:

    Wf : S1 : D1
    #Wf2 : S2 : d2
    Wf3 : S3 : D3
    Wf4 : S4 : d4

    using looping in unix i want to read the contents where it does not begin with hash.

    I want to obtain the output as

    Wf is S1 and D1;
    Wf3 is S3 and D3;
    Wf4 is S4 and d4;

    provide me with a shell scipt to do this

    Kind Regards
    P

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    14,922
    Code:
    awk "!/^#/{print}"
    -PatP
    Last edited by Pat Phelan; 12-20-12 at 19:24.
    In theory, theory and practice are identical. In practice, theory and practice are unrelated.

  3. #3
    Join Date
    Feb 2006
    Posts
    172
    Below is one way to do it in shell script:
    Code:
    # Script:  test.sh
    while IFS=":" read field1 field2 field3
    do
      if [ "${field1:0:1}" == "#" ]; then
        continue
      fi
      echo $field1 $field2 $field3
    done <t
    
    
    $ cat t
    Wf : S1 : D1
    #Wf2 : S2 : d2
    Wf3 : S3 : D3
    Wf4 : S4 : d4
    
    
    $ test.sh
    Wf S1 D1
    Wf3 S3 D3
    Wf4 S4 d4

  4. #4
    Join Date
    Nov 2011
    Posts
    5

    another requirement

    Thanks..But another requirement come up.
    In a file (testfile.lst) I have the contents as:

    Wf : S1 : D1 : U
    #Wf2 : S2 : d2 : V
    Wf3 : S3 : D3 : W
    #Wf6 : S6 : D6 : W

    Wf4 : S4 : d4 : X

    using looping in unix i want to read the contents where it does not begin with hash.

    I will pass an argument W(fourth field) with the shell script and I want to obtain the output as:

    Wf3 is S3 and D3
    Wf4 is S4 and d4

    When it first encountered W in the fourth column then that line and all succeeding lines in the file will comprise the output.


    provide me with a shell scipt to do this

    Kind Regards
    P

  5. #5
    Join Date
    Sep 2009
    Location
    Ontario
    Posts
    1,004
    Code:
    # Script:  test.sh
    firstW=0
    while IFS=":" read field1 field2 field3 field4
    do
      if [ "${field1:0:1}" == "#" ]; then
        continue
      fi
       if [ "$field4" =  "  W" ]
          then
          firstW=1
        fi
       if [ $firstW -eq 1 ]
      then
      echo $field1 is $field2 and $field3 
      fi
    done <t
    You will have to test whether field4 has a leading space since IFS is set to colon.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •