将字符串的一部分提取到bash中的变量 [英] Extracting part of a string to a variable in bash

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

问题描述

小白菜在这里,很抱歉,如果重新发布.我正在从文件中提取字符串,并以一行结尾,例如:

noob here, sorry if a repost. I am extracting a string from a file, and end up with a line, something like:

abcdefg:12345:67890:abcde:12345:abcde

假设它在一个名为testString的变量中 冒号之间的值的长度不是恒定的,但是我想将数字保存为第2个冒号和第3个冒号之间的变量,因为字符串可以用.所以在这种情况下,我将得到一个新变量,我们称其为extractNum,即67890.我认为我必须使用sed,但从未使用过它,并试图让我的头脑转转…… 有人可以帮忙吗?干杯

Let's say it's in a variable named testString the length of the values between the colons is not constant, but I want to save the number, as a string is fine, to a variable, between the 2nd and 3rd colons. so in this case I'd end up with my new variable, let's call it extractedNum, being 67890 . I assume I have to use sed but have never used it and trying to get my head around it... Can anyone help? Cheers

在旁注中,我使用find从字符串中提取整行,方法是搜索第一个字符串,在本例中为abcdefg部分.

On a side-note, I am using find to extract the entire line from a string, by searching for the 1st string of characters, in this case the abcdefg part.

推荐答案

这是另一种纯bash方式.当您的输入合理一致且在选择哪个部分时不需要太多灵活性时,效果很好.

Here's another pure bash way. Works fine when your input is reasonably consistent and you don't need much flexibility in which section you pick out.

extractedNum="${testString#*:}"     # Remove through first :
extractedNum="${extractedNum#*:}"   # Remove through second :
extractedNum="${extractedNum%%:*}"  # Remove from next : to end of string

您还可以在读取文件时过滤文件,例如,在while循环中:

You could also filter the file while reading it, in a while loop for example:

while IFS=' ' read -r col line ; do
    # col has the column you wanted, line has the whole line
    # # #
done < <(sed -e 's/\([^:]*:\)\{2\}\([^:]*\).*/\2 &/' "yourfile")

sed命令正在选择第二列,并从整行中用空格定界该值.如果您不需要整条线,只需删除空格+&从替换中删除行变量.您可以通过更改\ {2 \}位中的数字来选择任何列. (如果要在其中使用变量,请将命令放在双引号中.)

The sed command is picking out the 2nd column and delimiting that value from the entire line with a space. If you don't need the entire line, just remove the space+& from the replacement and drop the line variable from the read. You can pick any column by changing the number in the \{2\} bit. (Put the command in double quotes if you want to use a variable there.)

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

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