如何将 Shell 脚本中的部分字符串提取为变量 [英] How to Extract Parts of String in Shell Script into Variables

查看:47
本文介绍了如何将 Shell 脚本中的部分字符串提取为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 sh 中执行以下操作.

I am trying to do the following in sh.

这是我的文件:

foo
bar
Tests run: 729, Failures: 0, Errors: 253, Skipped: 0
baz

如何将 4 个数字提取到 4 个不同的变量中?我现在已经在 sed 和 awk 手册页上花了大约一个小时,而且我正在转动我的轮子.

How can I pull the 4 numbers into 4 different variables? I've spent about an hour now on sed and awk man pages and I'm spinning my wheels.

推荐答案

采用我之前的回答以使用 @chepner 建议的 heredoc 方法:

Adopting my prior answer to use the heredoc approach suggested by @chepner:

read run failures errors skipped <<EOF
$(grep -E '^Tests run: ' <file.in | tr -d -C '[:digit:][:space:]')
EOF

echo "Tests run: $run"
echo "Failures: $failures"
echo "Errors: $errors"
echo "Skipped: $skipped"

<小时>

或者(将其放入 shell 函数中以避免在脚本期间覆盖$@"):


Alternately (put this into a shell function to avoid overriding "$@" for the duration of the script):

unset IFS # assert default values
set -- $(grep -E '^Tests run: ' <in.file | tr -d -C '[:digit:][:space:]')
run=$1; failures=$2; errors=$3; skipped=$4

请注意,这只是安全的,因为以这种方式运行时,tr 的输出中不会出现 glob 字符;set -- $(something) 通常最好避免这种做法.

Note that this is only safe because no glob characters can be present in the output of tr when run in this way; set -- $(something) usually a practice better avoided.

现在,如果您为 bash 而不是 POSIX sh 编写代码,您可以在 shell 内部执行正则表达式匹配(假设在下面您的输入文件相对较短):

Now, if you were writing for bash rather than POSIX sh, you could perform regex matching internal to the shell (assuming in the below that your input file is relatively short):

#!/bin/bash
re='Tests run: ([[:digit:]]+), Failures: ([[:digit:]]+), Errors: ([[:digit:]]+), Skipped: ([[:digit:]]+)'
while IFS= read -r line; do
  if [[ $line =~ $re ]]; then
    run=${BASH_REMATCH[1]}
    failed=${BASH_REMATCH[2]}
    errors=${BASH_REMATCH[3]}
    skipped=${BASH_REMATCH[4]}
  fi
done <file.in

如果您的输入文件短,通过grep预先过滤它可能更有效,因此将最后一行更改为:

If your input file is not short, it may be more efficient to have it pre-filtered by grep, thus changing the last line to:

done < <(egrep -E '^Tests run: ' <file.in)

这篇关于如何将 Shell 脚本中的部分字符串提取为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆