1

I have a file log_file which has contents such as

CCO O-MR1 Sync:No:3:No:346:Yes
CCO P Sync:No:1:No:106:Yes
CCO P Checkout:Yes:1:No:10:No
CCO O-MR1 Checkout(2.2):Yes:1:No:10:No

I am trying to obtain the 4 fields based on ":" delimiter The script that I have is

#!/bin/bash
log_file=$1

for i in `cat $log_file` ; do
        echo $i
        field_a=`echo $i | awk -F '[:]' '{print $1}'`
        echo $field_a
        field_b=`echo $i | awk -F '[:]' '{print $2}'`
        echo $lfield_b
        ...
done

but the value that this code gives for field_a is wrong, it splits the line based on " " delimiter. echo $i also prints wrong value.

What else can I use to correct this?

1

1 Answer 1

5

This is covered in detail in BashFAQ #1. To summarize, use a while read loop with IFS set to contain (only) the characters that should be used to split fields.

while IFS=: read -r field_a field_b other_fields; do
  echo "field_a is $field_a"
  echo "field_b is $field_b"
  echo "Remaining fields are $other_fields"
done <"$log_file"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.