使用bash从一个txt文件获得第一个整数。

时间:2021-01-07 00:08:53

How could I (under ubuntu) get the first integer from a string and save that integer to a new text file in bash?

如何(在ubuntu下)从字符串中获取第一个整数,并将其保存到bash中的新文本文件中?

This line is in a bash loop I am using...

echo $line | tr -cd [:digit:] >> $line-num.txt

My string looks like this...

321#somewords-and-numbers32452352

321 # somewords-and-numbers32452352


Which is resulting in this...

这导致了……

32132452352

32132452352

How can I get just 321 as the output.

我怎么能得到321作为输出。

Thanks

谢谢

4 个解决方案

#1


1  

Using pure BASH:

使用纯BASH:

line='321#somewords-and-numbers32452352'
[[ "$line" =~ ^[^0-9]*([0-9]+) ]] && echo "${BASH_REMATCH[1]}"
321

Or using sed:

或者使用sed:

sed 's/^[^0-9]*\([0-9]\+\).*$/\1/' <<< "$line"
321

#2


1  

echo 'abc321#somewords-and-numbers32452352' | grep -oP '^[^0-9]*\K[0-9]+'

Output:

输出:

321

#3


0  

Use sed and a string match to return the first number in the string.

使用sed和字符串匹配返回字符串中的第一个数字。

echo $line | sed -e 's/^[^0-9]*\([0-9][0-9]*\).*/\1/'

echo $行| sed - e ' s / ^ \[^ 0 - 9]*([0 - 9][0 - 9]* \)。* / \ 1 /

The first part of the regular expression [^0-9]* is to removing any non-numeric leading characters if they are present.

的第一部分正则表达式[^ 0 - 9]*是删除任何非数字主要字符是否存在。

#4


0  

bash parameter expansion

bash参数扩展

s="321#somewords-and-numbers32452352"
t=${s%%[^[:digit:]]*}     # remove trailing non-digits
t=${t##*[^[:digit:]]}     # remove leading non-digits, if any
echo "$t"
321

#1


1  

Using pure BASH:

使用纯BASH:

line='321#somewords-and-numbers32452352'
[[ "$line" =~ ^[^0-9]*([0-9]+) ]] && echo "${BASH_REMATCH[1]}"
321

Or using sed:

或者使用sed:

sed 's/^[^0-9]*\([0-9]\+\).*$/\1/' <<< "$line"
321

#2


1  

echo 'abc321#somewords-and-numbers32452352' | grep -oP '^[^0-9]*\K[0-9]+'

Output:

输出:

321

#3


0  

Use sed and a string match to return the first number in the string.

使用sed和字符串匹配返回字符串中的第一个数字。

echo $line | sed -e 's/^[^0-9]*\([0-9][0-9]*\).*/\1/'

echo $行| sed - e ' s / ^ \[^ 0 - 9]*([0 - 9][0 - 9]* \)。* / \ 1 /

The first part of the regular expression [^0-9]* is to removing any non-numeric leading characters if they are present.

的第一部分正则表达式[^ 0 - 9]*是删除任何非数字主要字符是否存在。

#4


0  

bash parameter expansion

bash参数扩展

s="321#somewords-and-numbers32452352"
t=${s%%[^[:digit:]]*}     # remove trailing non-digits
t=${t##*[^[:digit:]]}     # remove leading non-digits, if any
echo "$t"
321