如果我正确地回答了您的问题,请您尝试以下操作。
echo "150%" | sed 's/\([^%]*\)%.*/\1/'
它将输出为150
。现在,如果我们使用echo "150"
进行如下操作:
echo "150" | sed 's/\([^%]*\)%.*/\1/'
输出仍为150
或者,如果您也想在输出使用中使用%
(在看到@oguz ismail的回答后添加此选项):
echo "150%" | sed 's/\([^%]*\)%.*/\1%/'
OR
echo "150" | sed 's/\([^%]*\)%.*/\1%/'
sed
命令的解释: 以下是sed
命令的解释,仅用于解释目的。
echo "150%" | ##echoing 150% and using pipe(|) sending its standard output as input to sed command.
sed ' ##Starting sed command from here.
s ##Using s option for using substitution.
/\([^%]*\)%.* ##Using memory buffer capability by taking everything before 1st occurrence of % and save it into (...) escaping \( and \) to remove its special meaning. Then mentioning % and everything else.
/\1/ ##Now mentioning \1 means substitute complete Line with only matched 1st memory buffer value.
'
使用awk
的答案:如果您可以使用awk
的答案:
echo "150%" | awk 'BEGIN{FS=OFS="%"} {print $1,""}'
,
捕获数字部分,在替换内容后附加%
。例如:
sed -n 's/^\([0-9]\{1,\}\)%*/\1%/p'
使用GNU sed可以将其缩短为:
sed -En 's/^([0-9]+)%*/\1%/p'
我宁愿使用bash的regex匹配机制而不是sed来验证和清除这种说法。
,
答案的问题是您使用“ \ d”,而sed不提供该正则表达式扩展名。不过,您可以使用Posix字符类,因此可以执行以下操作:
size_t
,
您得到了您想要的sed答案,但是仅供参考,您实际上不会将sed用于这样的工作,而只是用shell替代:
$ cat tst.sh
#!/usr/bin/env bash
function increase {
if [ "$#" -eq 2 ]; then
echo pactl set-sink-volume "$@"
elif [ "$#" -eq 1 ]; then
echo pactl set-sink-volume 0 "${1%\%}%"
fi
}
increase "$@"
$ ./tst.sh 3 4
pactl set-sink-volume 3 4
$ ./tst.sh 150
pactl set-sink-volume 0 150%
$ ./tst.sh 150%
pactl set-sink-volume 0 150%
,
如果要使用GNU sed,可以这样做:
echo "150%" | sed -nr 's/([[:digit:]]+).?/\1/p'
150
echo "150%" | sed -nr 's/([[:digit:]]+).?/\1%/p'
150%
选项“ -r”用于扩展正则表达式(无需频繁使用“ \”)
本文链接:https://www.f2er.com/3130296.html