insert '.' between all characters in grep

2019-08-13 13:08发布

I want to insert '.' between every character in a given input string and then use it as an argument in a pipe

I am doing one of the following:

tail -f file.txt | grep -a 'R.e.s.u.l.t.'
tail -f file.txt | awk '/R.e.s.u.l.t./'

How can I just type 'Result' and pass it as the regex argument to grep when receiving input from a buffer created by tail -f by using additional bash default functions

2条回答
▲ chillily
2楼-- · 2019-08-13 14:05

The awk version:

tail -f file.txt | 
awk -v word="Result" '
    BEGIN {gsub(/./, "&.", word); sub(/\.$/, "", word)} 
    $0 ~ word
'
查看更多
\"骚年 ilove
3楼-- · 2019-08-13 14:07
tail -f file.txt | grep -a -e "$(echo Result | sed 's/./&./g')"

This echoes the word Result as input to sed (consider a here-string instead), which replaces each character with itself followed by a ., and then the output is used as the search expression for grep. The -e protects you from mishaps if you want to search for -argument with the dots, for example. If the string is in a variable, then you'd use double quotes around that, too:

result="Several Words"
tail -f file.txt | grep -a -e "$(echo "$result" | sed 's/./&./g')"
查看更多
登录 后发表回答