Reputation: 31
Data in the log file goes like this
username - yyyy-mm-dd, HH:MM:SS
Now how to seperate username, date and time?
I tried using.
while IFS=" - |, " read G1 G2 G3
But this considers the hyphen between the date.. any idea?
EDIT: I actually found a method .....
I used
while IFS="-""," read G1 G2 G3 G4
And G1 was the username , G2 was - G3 was date and G4 was the time..
I couldn't understand how this works.. but it worked
Thanks
Upvotes: 3
Views: 2921
Reputation: 7801
Another approach is to use a dummy variable to hold the dash -
and do a Parameter Expansion to remove the trailing comma ,
e.g. "${date%,}"
while read -r username _ date time; do
echo "$username" "${date%,}" "$time"
done < log.txt
Upvotes: 0
Reputation: 141493
How to use IFS with multiple delimiters?
It is possible to use IFS with multiple single character delimiters. Any character in the set in IFS is considered a delimiter. The IFS=" - |, "
is equal to IFS=" -|,"
- repeated characters are ignored.
It's not possible to use IFS splitting with any multi-character delimiters.
any idea?
Use another tool and do the splitting yourself. You could match the line with regex with bash [[ =~
matching or in sed
or use awk
to parse the line or use other tools.
Upvotes: 1
Reputation: 785531
You may try this script in bash
:
while IFS= read -r && read G1 G2 G3 <<< "${REPLY//[,-]/}"; do
echo "[$G1][$G2][$G3]"
done < file.log
Output:
[username][yyyymmdd][HH:MM:SS]
Here we are reading full line in internal REPLY
variable first then we use another read
to get values in 3 variables after cleaning up $REPLY
by removing -
and ,
upfront.
Upvotes: 2