处理搜索字符串中的元字符 [英] Handling metacharacters in search strings
问题描述
我有一个用户输入可用于可能包含元字符的搜索字符串中。
例如, C#或者C ++在一个函数中我的grep命令是:b
$ b
grep -E$ 1 | $ 2test.txt
直接替换:
grep -EC \ + \ + | testWordtest.txt
grep -EC\#| testWord test.txt
第一条线条很好,但不是第二条。
奇怪的是,#被完全忽略了。
如果没有直接替换,两者都会用c接收任何东西,接着是testWord,而不是c ++和c##
我试着用sed来处理它。 b
$ b
$ temp =`echo $ 1 | sed's / [\#\!\& \; \\\\\\\\ | \ * \?\〜\< \> \ ^ \(\)\ [\] \ {\} \ $ \ + \\] / \\& / g'`
但它不能正常工作
或者有其他方法可以用元字符处理用户输入吗?
$ b
在此先感谢
如果您将输入作为参数传递给脚本
p> #!/ bin / bash
input1 =$ 1
input2 =$ 2
读取-r行
做
在
* $ input1 * | * $ input2 *)echofound:$ line;;
esac
完成<BooksDB.txt
输出
$ cat文件
这是一行
这一行有C ++和C#
这行只有C ++,就是它
这行只有C#,就是它
这是结束行Caa
$ ./shell.sh C ++ C#
found:这行有C ++和C#
找到:这行只有C ++,就是它
找到了:这行只有C#,就是这样
如果您从阅读中获得输入
<$输入input1:input1
读-p输入input2:input2
读取-r行
执行
* $ input1 | * $ input2 *)echofound:$ line;;
esac
完成<BooksDB.txt
I have a user input that would be used in a search string that may contain a metacharacter
For e.g. C# or C++
my grep command in a function was:
grep -E "$1|$2" test.txt
under direct replacement:
grep -E "C\+\+|testWord" test.txt
grep -E "C\#|testWord" test.txt
the first caught the lines fine but not the second. Strangely, # was completely ignored. Without direct replacement, both catch anything with c followed by testWord instead of c++ and c# respectively
I've tried handling it using sed
$temp = `echo $1 | sed 's/[\#\!\&\;\`\"\'\|\*\?\~\<\>\^\(\)\[\]\{\}\$\+\\]/\\&/g'`
but it doesn't work right. Or is there any other way to handle user input with metacharacters?
Thanks in advance
if you are passing the input as arguments to the script
#!/bin/bash
input1="$1"
input2="$2"
while read -r line
do
case "$line" in
*$input1*|*$input2* ) echo "found: $line";;
esac
done <"BooksDB.txt
"
output
$ cat file
this is a line
this line has C++ and C#
this line has only C++ and that's it
this line has only C# and that's it
this is end line Caa
$ ./shell.sh C++ C#
found: this line has C++ and C#
found: this line has only C++ and that's it
found: this line has only C# and that's it
if you are getting input from read
read -p "Enter input1:" input1
read -p "Enter input2:" input2
while read -r line
do
case "$line" in
*$input1|*$input2* ) echo "found: $line";;
esac
done <"BooksDB.txt"
这篇关于处理搜索字符串中的元字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!