我正在尝试在文件中搜索模式(字符串)。我想打印线条和线条中找到图案的位置。
到目前为止,我能够找到我的模式的第一个字母的第一个外观。
但我想找到整个模式的所有出现
#!/bin/bash
file=$1
awk -v s="$2" 'i=index($0, s){print "line: " NR, "pos: " i}' "$file"
$ ./search.sh test.txt GA
1 GAGAGAGAGA
2 CTCTCTCTCT
3 TATATATATA
4 CGCGCGCGCG
5 CCCCCCCCCC
6 GGGGGGGGGG
7 AAAAAAAAAA
8 TTTTTTTTTT
9 TGATTTTTTT
10 CCCCCCCCGA
当我使用test.txt运行上述命令行调用时,打印结果为:
line: 1 pos: 1
line: 4 pos: 2
line: 6 pos: 1
line: 9 pos: 2
line: 10 pos: 9
这显然只是G的第一场比赛。
有没有办法稍微修改我的awk命令,或者我是在想一个完全错误的方向?
答案 0 :(得分:2)
关注awk可能对你有帮助。
cat search.sh
Input_file="$1"
text_to_be_searched="$2"
awk -v var="$text_to_be_searched" '{
while($0){
match($0,var);
q=q?q+length(var):RSTART;
if(RSTART){
val=val? val "," q:"Line:"NR FS "pos:" q;
$0=substr($0,RSTART+RLENGTH);
}
else{
if(val){
print val};
q=val="";
next
}
};
print val;
q=val=""
}
END{
if(val){
print val
}}
' "$Input_file"
./search.sh test.txt GA
输出如下。
Line:1 pos:1,3,5,7,9
Line:9 pos:2
Line:10 pos:9
答案 1 :(得分:1)
使用Grep
<强>的test.txt 强>
GAGAGAGAGA
CTCTCTCTCT
TATATATATA
CGCGCGCGCG
CCCCCCCCCC
GGGGGGGGGG
AAAAAAAAAA
TTTTTTTTTT
TGATTTTTTT
CCCCCCCCGA
<强> search.sh 强>
#!/bin/bash
while read -r line; do
((++i))
echo "$line" | grep -bon "$2" | sed -r "s@^([0-9]+):([0-9]+):.*@Line: $i, Position: \2@g"
done < "$1"
<强>输出强>
darby@Debian:~/Scrivania$ bash search.sh test.txt GA
Line: 1, Position: 0
Line: 1, Position: 2
Line: 1, Position: 4
Line: 1, Position: 6
Line: 1, Position: 8
Line: 9, Position: 1
Line: 10, Position: 8
darby@Debian:~/Scrivania$
注意强>
位置索引从零开始。
答案 2 :(得分:-1)
使用perl
$ perl -lne 'while(/GA/g){print "line: $. pos: $-[0]"}' ip.txt
line: 1 pos: 0
line: 1 pos: 2
line: 1 pos: 4
line: 1 pos: 6
line: 1 pos: 8
line: 9 pos: 1
line: 10 pos: 8
$ perl -lne 'while(/GA/g){print "line: $. pos: ", $-[0]+1}' ip.txt
line: 1 pos: 1
line: 1 pos: 3
line: 1 pos: 5
line: 1 pos: 7
line: 1 pos: 9
line: 9 pos: 2
line: 10 pos: 9
来自perldoc
$ - [0]是上次成功比赛开始的偏移量
$。访问的最后一个文件句柄的当前行号。
while(/GA/g)
迭代所有匹配
传递变量
$ s='GAT' perl -lne 'while(/$ENV{s}/g){print "line: $. pos: $-[0]"}' ip.txt
line: 9 pos: 1