bash - 提取与模式匹配的部分行

标签 bash

我有一个配置文件,需要使用 bash 解析出一些值
例如。里面的config.txt

some_var= Not_needed
tests= spec1.rb spec2.rb spec3.rb
some_other_var= Also_not_needed

基本上,我只需要获取“spec1.rb spec2.rb spec3.rb”,而无需从该行中删除所有其他行和“tests=”。

我有这个并且它可以工作,但我希望有一个更简单的方法来做到这一点。

while read run_line; do
if [[ $run_line =~ ^tests=* ]]; then
  echo "FOUND"
  all_selected_specs=`echo ${run_line} | sed 's/^tests= /''/'`
fi
done <${config_file}
echo "${all_selected_specs}"

最佳答案

all_selected_specs=$(awk -F '= ' '$1=="tests" {print $2}' "$config_file")

使用 "= " 字段分隔符,查找第一个字段为 tests 的行并打印第二个字段。

关于bash - 提取与模式匹配的部分行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43900803/

相关文章:

regex - 将显示的终端输出保存到格式良好的文件中

bash - 设置或更改光标的垂直位置

git - 如何从 `commit-msg` git hook 中打开终端编辑器

Linux 模式从 ifconfig 的接口(interface)中提取 RX 数据包的编号

Linux 排序不适用于负 float

bash - 对某些目录 makefile 中的文件进行简单循环

python - 逐行打印 SSH 输出,而不是一次打印所有内容

Bash - 将字符串转换为日期

linux - 用于接受管道命令的 Ubuntu 脚本

bash - CircleCI 权限被拒绝运行 bash 脚本