我对在grep (bash)中使用正则表达式有一些基础知识。但是我想以另一种方式使用正则表达式。
例如,我有一个包含以下条目的文件:
line_one=[0-3]
line_two=[4-6]
line_three=[7-9]
现在,我想使用bash来确定某个特定数字与哪一行匹配。例如:
grep 8 file
应返回:
line_three=[7-9]
注意:我知道"grep 8文件“的例子没有意义,但我希望它能帮助理解我想要实现的目标。
谢谢你的帮助,马塞尔
发布于 2017-01-16 03:06:11
正如其他人指出的那样,awk
是实现这一目标的正确工具:
awk -F'=' '8~$2{print $0;}' file
..。如果你想让这个工具看起来更像grep,一个快速的bash包装器:
#!/bin/bash
awk -F'=' -v seek_value="$1" 'seek_value~$2{print $0;}' "$2"
它的运行方式如下:
./not_exactly_grep.sh 8 file
line_three=[7-9]
发布于 2017-01-16 03:09:25
这可以在原生bash中使用语法[[ $value =~ $regex ]]
来测试:
find_regex_matching() {
local value=$1
while IFS= read -r line; do # read from input line-by-line
[[ $line = *=* ]] || continue # skip lines not containing an =
regex=${line#*=} # prune everything before the = for the regex
if [[ $value =~ $regex ]]; then # test whether we match...
printf '%s\n' "$line" # ...and print if we do.
fi
done
}
...used as:
find_regex_matching 8 <file
...or,要使用您的示例输入内联来测试它:
find_regex_matching 8 <<'EOF'
line_one=[0-3]
line_two=[4-6]
line_three=[7-9]
EOF
...which正确地发出:
line_three=[7-9]
如果愿意,您可以将printf '%s\n' "$line"
替换为printf '%s\n' "${line%%=*}"
,以便仅打印密钥(=
之前的内容)。有关所涉及语法的概要,请参阅the bash-hackers page on parameter expansion。
发布于 2017-01-16 03:01:31
我的第一印象是,这不是grep的任务,可能是awk的任务。
尝试使用grep执行某些操作时,我只看到以下内容:
for line in $(cat file); do echo 8 | grep "${line#*=}" && echo "${line%=*}" ; done
使用while读取文件(以下备注):
while IFS= read -r line; do echo 8 | grep "${line#*=}" && echo "${line%=*}" ; done < file
https://stackoverflow.com/questions/41664616
复制相似问题