将bash变量作为模式传递给awk [英] Passing bash variable as a pattern to awk
问题描述
我想知道如何将bash variable
作为pattern
传递给awk
.
我已经阅读了几个Q/A,它们往往回答相同的问题,但是,没有一个解决了我的问题(可能是我遗漏了一些东西!).
I would like to know how to pass a bash variable
as a pattern
to awk
.
I have read several Q/As which tend to answer the same question, however, none of them solved my problem (probably, I am missing something!).
我有几个这样的文件:
1 9909 23121
1 23121 561510
3 75879819 75902940
3 75902940 75916152
4 75916152 75982212
3 75982212 75998727
22 82964754 83232297
X 59962662 60745473
,我想创建不同的文件,每个文件都包含相同的起始模式,我只想提取第2列,例如一个文件包含所有以第一个开头的行的第2列,另一个文件包含所有以X开头的行的第2列,等等.
and I want to create different files each containing same starting pattern and I only want to extract column 2 e.g. a file containing column 2 of all the rows starting with one, the other file containing column 2 of the rows starting with X etc.
我的代码如下:
for x in *.CNVs; do
for y in `seq 22` X Y; do
awk '/^$y/ {print $2}' $x > freec_${x}_${y}_st.txt;
done;
done;
我也尝试过使用-v
选项,例如:
I have also tried using -v
option like this:
for x in *.CNVs; do
for y in `seq 22` X Y; do
awk -v pattern="{$y}" '/^pattern/ {print $2}' $x > freec_${x}_${y}_st.txt;
done;
done;
我没有收到任何错误,所有文件均已创建;但是,它们都是空的!任何建议,不胜感激!
I don't get any error, all the files are created; however, they are all empty! Any suggestion is much appreciated!
[编辑]
我发现了使用grep
的更整洁的方式(以前,我认为它不能通过grep
来完成!):
[Edit]
I found a neater way using grep
(before, I was thinking that it cannot be done by grep
!):
for x in *.CNVs; do
for y in `seq 22` X Y; do
grep "^${y}\s" $x | cut -f2 > ${x}_${y}_st.txt;
done;
done;
使用grep
很有帮助,因为通过使用\s
,我可以区分以2、21和22等开头的行.
Using grep
is helpful since by using \s
, I can discriminate between line starting with 2, 21 and 22 etc.
推荐答案
变量未使用正则表达式文字(/.../
)进行扩展.您需要使用~
运算符和字符串文字.
Variables aren't expanded in regexp literals (/.../
). You need to use the ~
operator and string literals.
awk -v pattern="$y" '$0 ~ "^"pattern {print $2}' "$x" > "freec_${x}_${y}_st.txt"
您还需要注意任何模式元字符/等.在模式中.
You also need to be careful with any pattern metacharacters/etc. in the pattern.
这篇关于将bash变量作为模式传递给awk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!