bash 如何在awk中获取子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2667579/
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
How to get a substring in awk
提问by lugte098
This is one line of the input file:
这是输入文件的一行:
FOO BAR 0.40 0.20 0.40 0.50 0.60 0.80 0.50 0.50 0.50 -43.00 100010101101110101000111010
FOO 酒吧 0.40 0.20 0.40 0.50 0.60 0.80 0.50 0.50 0.50 -43.00 100010101101110101000111010
And an awk command that checks a certain position if it's a "1" or "0" at column 13 Something like:
还有一个 awk 命令,用于检查某个位置是否在第 13 列是“1”或“0” 类似于:
awk -v values="${values}" '{if (substr(,1,1)==1) printf values,,,,,,,,,,,,}' foo.txt > bar.txt
The values variable works, but i just want in the above example to check if the first bit if it is equal to "1".
values 变量有效,但我只想在上面的示例中检查第一位是否等于“1”。
EDIT
编辑
Ok, so I guess I wasn't very clear in my question. The "$13" in the substr method is in fact the bitstring. So this awk wants to pass all the lines in foo.txt that have a "1" at position "1" of the bitstring at column "$13". Hope this clarifies things.
好的,所以我想我的问题不是很清楚。substr 方法中的“$13”实际上是位串。所以这个 awk 想要传递 foo.txt 中所有在列“$13”的位串的位置“1”处有“1”的行。希望这能澄清事情。
EDIT 2
编辑 2
Ok, let me break it down real easy. The code above are examples, so the input line is one of MANY lines. So not all lines have a 1 at position 8. I've double checked to see if a certain position has both occurences, so that in any case I should get some output. Thing is that in all lines it doesn't find any "1"'s on the posistions that I choose, but when I say that it has to find a "0" then it returns me all lines.
好吧,让我把它分解得很简单。上面的代码是示例,因此输入行是许多行之一。因此,并非所有行在位置 8 处都有 1。我已经仔细检查了某个位置是否同时出现了这两种情况,因此无论如何我都应该得到一些输出。事情是,在所有行中,它在我选择的位置上找不到任何“1”,但是当我说它必须找到“0”时,它会返回所有行。
回答by ghostdog74
$ cat file
FOO BAR 0.40 0.20 0.40 0.50 0.60 0.80 0.50 0.50 0.50 -43.00 100010101101110101000111010
FOO BAR 0.40 0.20 0.40 0.50 0.60 0.80 1.50 1.50 1.50 -42.00 100010111101110101000111010
$ awk 'substr(,8,1)==1{ print "1->"##代码## } substr(,8,1)==0{ print "0->"##代码## }' file
0->FOO BAR 0.40 0.20 0.40 0.50 0.60 0.80 0.50 0.50 0.50 -43.00 100010101101110101000111010
1->FOO BAR 0.40 0.20 0.40 0.50 0.60 0.80 1.50 1.50 1.50 -42.00 100010111101110101000111010

