在 Bash 中使用 2 个不同的分隔符拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25163486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:03:20  来源:igfitidea点击:

Split string using 2 different delimiters in Bash

regexstringbashsplitifs

提问by geekyjazzy

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

我正在尝试根据 2 个分隔符 - 空格和 \ 在 BASH 中拆分字符串。这是字符串:-

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:-

我希望它分成 3 部分,如下所示:-

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 :-

我试过使用 IFS,它很好地分割了第一个。但是第二次拆分一些如何删除“\”并粘贴整个部分,我将拆分为:-

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:-

我使用的 IFS 如下:-

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.

提前致谢。

回答by Mark Setchell

I think you need this:

我认为你需要这个:

IFS=' |\' read -ra array_1 <<< "$var_result"

回答by cryptobionic

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 }');
echo $field1;
echo $field2;
echo $field3;