bash Awk 使用带子字符串的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25492826/
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
Awk using index with Substring
提问by clear.choi
I have one command to cut string.
我有一个切割字符串的命令。
I wonder detail of control index of command in Linux "awk"
我想知道 Linux "awk" 中命令的控制索引的详细信息
I have two different case.
我有两种不同的情况。
I want to get word "Test" in below example string.
我想在下面的示例字符串中得到“测试”这个词。
1. "Test-01-02-03"
2. "01-02-03-Test-Ref1-Ref2
First one I can get like
第一个我可以得到
substr('Test-01-02-03',0,index('Test-01-02-03',"-"))
-> Then it will bring result only "test"
How about Second case I am not sure how can I get Test in that case using index function.
第二种情况怎么样我不确定在那种情况下如何使用索引函数获得测试。
Do you have any idea about this using awk?
你对这个使用 awk 有什么想法吗?
Thanks!
谢谢!
采纳答案by Ed Morton
This is how to use index() to find/print a substring:
这是使用 index() 查找/打印子字符串的方法:
$ cat file
Test-01-02-03
01-02-03-Test-Ref1-Ref2
$ awk -v tgt="Test" 's=index($ awk -v tgt="Test" 'match(awk -v tgt="Test" '
function strmatch(source,target) {
SSTART = index(source,target)
SLENGTH = length(target)
return SSTART
}
strmatch(##代码##,tgt){print substr(##代码##,SSTART,SLENGTH)}
' file
,tgt){print substr(##代码##,RSTART,RLENGTH)}' file
Test
Test
,tgt){print substr(##代码##,s,length(tgt))}' file
Test
Test
but that may not be the best solution for whatever your actual problem is.
但这可能不是解决您的实际问题的最佳解决方案。
For comparison here's how to do the equivalent with match() for an RE:
为了进行比较,这里是如何使用 match() 对 RE 进行等效操作:
##代码##and if you like the match()
synopsis, here's how to write your own function to do it for strings:
如果您喜欢match()
概要,这里是如何编写自己的函数来为字符串执行此操作:
回答by Etan Reisner
If these lines are the direct input to awk
then the following work:
如果这些行是直接输入,awk
那么以下工作:
echo 'Test-01-02-03' | awk -F- '{print $1}'
# First fieldecho '01-02-03-Test-Ref1-Ref2' | awk -F- '{print $NF-2}'
# Third field from the end.
echo 'Test-01-02-03' | awk -F- '{print $1}'
# 第一个字段echo '01-02-03-Test-Ref1-Ref2' | awk -F- '{print $NF-2}'
# 末尾的第三个字段。
If these lines are pulled out of a larger line in an awk script and need to be split again then the following snippets will do that:
如果将这些行从 awk 脚本中的较大行中拉出并需要再次拆分,则以下代码段将执行此操作:
str="Test-01-02-03"; split(str, a, /-/); print a[1]
str="01-02-03-Test-Ref1-Ref2"; numfields=split(str, a, /-/); print a[numfields-2]
str="Test-01-02-03"; split(str, a, /-/); print a[1]
str="01-02-03-Test-Ref1-Ref2"; numfields=split(str, a, /-/); print a[numfields-2]