bash 如何在shell脚本中的模式之前提取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24926606/
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 10:56:38  来源:igfitidea点击:

How to extract string before pattern in shell script

bashshell

提问by Kumaran

I have a variable which has contents like this

我有一个变量,它的内容是这样的

line 1
line 2
line 3
======
line 4
line 5
line 6
======
.........
line n
======

第 1
行 2
行 3
======
第 4
行 5
第 6 行
======
..........
第 n 行
======

Now i want to extract lines before all occurence of '======' pattern and i want to assign it to each variable.
Expected output
Var1=line 1
line 2
line 3
Var2=line 4
line 5
line 6
...........
Var_n=line n

Storing it in an array is also accepted
How to do it?

现在我想在所有 '======' 模式出现之前提取行,我想将它分配给每个变量。
预期输出
Var1=line 1
line 2
line 3
Var2=line 4
line 5
line 6
.....
Var_n=line n

也接受数组存储
怎么做?

回答by Jayesh Bhoi

You can achieve using parameter expansion as like

您可以像这样使用参数扩展来实现

str="mystring:yourstring"  //here assume ":" is pattern
var=${str%:*}
echo $var

For your information you can use #instead %to get string after pattern

为了您的信息,您可以使用#,而不是%模式之后得到的字符串

var=${str#*:}

回答by David C. Rankin

#!/bin/bash

# original string
str="some lines1 ====== some lines2 ======"

# parse the string
v1="${str%% =*}"  # beginning at right, remove all to ' ='
tmp="${str% =*}"  # beginning at right, remove first occurrence of ' =*'
v2="${tmp##*= }"  # beginning at left,  remove all to '= '

# print the string and variable
echo "str: $str"
echo " v1: $v1"
echo " v2: $v2"

exit 0

output:

输出:

$ bash somelines.sh
str: some lines1 ====== some lines2 ======
 v1: some lines1
 v2: some lines2