string - 读取包含字符串的行(Bash)

标签 string bash file variables contain

我有一个文件,它是这样的:

Device: name1
random text
Device: name2
random text
Device: name3
random text

我有一个变量:MainComputer

我想得到什么(对于每个名字,我有 40 个名字):

   MainComputer -> name1
   MainComputer -> name2
   MainComputer -> name3

我有什么:

var="MainComputer"   
var1=$(awk '/Device/ {print $3}' file)
echo "$var -> $var1"

这只给出了箭头“->”和第一个变量的链接,我希望它们用于其他 40 个变量...

谢谢!

最佳答案

让我向您介绍 awk:

$ awk '/Device/ {print $2}' file
name1
name2
name3

这会在包含 Device 的行中打印第二个字段。如果要检查它们是否以 Device 开头,可以使用 ^Device:

更新

要获得您在编辑的问题中提到的输出,请使用:

$ awk -v var="MainComputer" '/Device/ {print var, "->", $2}' a
MainComputer -> name1
MainComputer -> name2
MainComputer -> name3

它通过-v提供变量名,然后打印该行。


找到一些关于您的脚本的评论:

file="/scripts/file.txt"
while read -r line
do
     if [$variable="Device"]; then # where does $variable come from? also, if condition needs tuning
     device='echo "$line"' #to run a command you need `var=$(command)`
echo $device #this should be enough
fi
done <file.txt #why file.txt if you already stored it in $file?

检查 bash string equality查看 [[ "$variable"= "Device"]] 的语法(或类似语法)。

另外,你可以说 while read -r name value,这样 $value 就会包含从第二个值开始的值。

关于string - 读取包含字符串的行(Bash),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29796979/

相关文章:

javascript - Jquery 字符串 + 对象 + 字符串

java - BigInteger 在合理的时间内串起来

linux - java.lang.NoSuchMethodError : No such DSL method 'bash' found among steps 错误

file - Grails在 war 中进行文件上传管理

C : Best way to go to a known line of a file

java - 如何在Super CSV java中处理csv文件中的空字符串?

java - 如何将逗号插入整数

java - WSL Bash 未在 PATH 中找到 java

linux - Bash:从文件中读取标准输入并将标准输出写入文件

c++ - 如何使用 QDataStream 从文件中读取二进制数据?