本文介绍了在 egrep 的正则表达式中管道 bash 输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要运行的脚本

#!/bin/bash

charlist=$1 #possible input:cat
wordlength=$2 #possible input: 3

cat ./nounlist | egrep [${charlist}]{${wordlength}}

output: nothing.# 应该捕获以下内容(使用命令行)

output: nothing.# should've caught the following(using command line)

$ cat nounlist | egrep "[cat]{3}"
act
cat's_cradle
cat
cat-o'-nine-tails
cat's-paw
Sno-cat
act
act
act
act
rat-a-tat-tat
cat
cat's-claw
cat's_foot
cat's-ear
cat's-tail
cat's-ear
cat's_eye

基本上,我正在尝试编写一个脚本,该脚本采用两个参数(wordlist、wordlength)并获取名词列表中由 wordlist 中的字符组成并具有 wordlength 变量长度的所有单词.我想知道的是如何将bash变量作为字符串放入egrep的正则表达式中?

basically I am trying to write a script that takes two arguments(wordlist, wordlength) and fetch all the words in the nounlist that consist of the char in the wordlist and has the length of wordlength variable. What I want to know is how to put bash variables in egrep's regular expression as strings?

谢谢!

推荐答案

您需要将参数用双引号括起来,这样 Bash 就不会尝试处理反斜杠,并移动第二个 after {${wordlength}}:

You need to wrap the argument in double-quotes so that Bash doesn't try to handle the backslashes, and move the second  to after the {${wordlength}}:

cat ./nounlist | egrep "[${charlist}]{${wordlength}}"

(如果你运行 echo ,你会看到它只打印 b.这是因为 Bash 假设 是否有防止 b 具有任何特殊含义;因此将其删除.)

(If you run echo , you'll see that it just prints b. This is because Bash assumes that the is there to prevent b from having any special meaning; so it removes it.)

这篇关于在 egrep 的正则表达式中管道 bash 输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:38