Split string using 2 different delimiters in Bash
Asked Answered
S

2

5

I am trying to split a string in BASH based on 2 delimiters - Space and the \. This is the string:-

var_result="Pass results_ADV__001__FUNC__IND\ADV__001__FUNC__IND_08_06_14_10_04_34.tslog"

I want it to split in 3 parts as follows:-

part_1=Pass
part_2=results_ADV__001__FUNC__IND
part_3=ADV__001__FUNC__IND_08_06_14_10_04_34.tslog

I have tried using IFS and it splits the first one well. But the second split some how removes the "\" and sticks the entire part and I get the split as :-

test_res= Pass
log_file_info=results_ADV__001__FUNC__INDADV__001__FUNC__IND_08_06_14_10_04_34.tslog

The IFS I used is as follows:-

echo "$var_result"
IFS=' ' read -a array_1 <<< "$var_result"
echo "test_res=${array_1[0]}, log_file_info=${array_1[1]}"

Thanks in advance.

Septempartite answered 6/8, 2014 at 14:47 Comment(2)
You need to pass -r to read to tell it not to evaluate escapes.Fasta
@EtanReisner you were right in both the cases. I missed the use of -r. Thank you. :)Septempartite
P
11

I think you need this:

IFS=' |\\' read -ra array_1 <<< "$var_result"
Palladous answered 6/8, 2014 at 14:56 Comment(1)
Can someone please give answer for #46556702 ?Cutter
P
0

This should do it

#!/bin/bash
var_result="Pass results_ADV__001__FUNC__IND\ADV__001__FUNC__IND_08_06_14_10_04_34.tslog"
field1=$(echo "$var_result" | awk -F ' ' '{print $(NF-1)}');
field2=$(echo "$var_result" | awk -F  \\ '{print $(NF-1)}');
field1=$(echo "$field1" | awk -F ' ' '{print $(NF-1)}');
field3=$(echo "$var_result" | awk -F  \\ '{print $2}');
echo $field1;
echo $field2;
echo $field3;
Perrins answered 6/8, 2014 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.