String 读取包含字符串的行(Bash)
我有一个文件,它是这样的:String 读取包含字符串的行(Bash),string,bash,file,variables,contain,String,Bash,File,Variables,Contain,我有一个文件,它是这样的: Device: name1 random text Device: name2 random text Device: name3 random text 我有一个变量:主计算机 我想要得到什么(对于每个名字,我有40个名字): 我所拥有的: var="MainComputer" var1=$(awk '/Device/ {print $3}' file) echo "$var -> $var1" 这只给出了箭头“->”和第一个变量的链接,我希望其他4
Device: name1
random text
Device: name2
random text
Device: name3
random text
我有一个变量:主计算机
我想要得到什么(对于每个名字,我有40个名字):
我所拥有的:
var="MainComputer"
var1=$(awk '/Device/ {print $3}' file)
echo "$var -> $var1"
这只给出了箭头“->”和第一个变量的链接,我希望其他40个变量都有它们
无论如何谢谢你 让我向您介绍一下
awk
:
$ awk '/Device/ {print $2}' file
name1
name2
name3
这将在包含设备的行上打印第二个字段。如果要检查它们是否以设备开头,可以使用^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?
file=“/scripts/file.txt”
而read-r行
做
如果[$variable=“Device”];那么#$variable从何而来?此外,如果条件需要调整
device='echo“$line”'#要运行命令,需要'var=$(命令)`
echo$设备#这应该足够了
fi
完成或者,让我向您介绍grep和cut:
$ grep "^Device:" $file | cut "-d " -f2-
我猜cut“-d”-f2-
是一个打字错误。你可能想说cut-d”“
@fedorqui:它们有什么不同?这两种方法都将导致cut
的参数值相同<代码>-d”“
对我来说更易读。但是从bash
的角度来看,两者是相同的。(对于cygwin
的cut.exe
,如果从cmd
运行cmd
会将“
传递给子进程,则情况可能并非如此。)确切地说,您可以选择您最喜欢的版本。@fedorqui:是的,“-d”
是不寻常的,但正如@anishsane所指出的,-d”“
在cut
看到它时会产生完全相同的字符串:在shell执行引号删除后,这两种形式都会产生一个包含d
后跟空格的参数。@mklement0 fantastic,没有意识到它。”。为了让它“持久化”,我只是把它作为一个答案发布在中。对不起,我忘记了这个:variable=“Device”file=“/scripts/file.txt”,而read-r line do if[$variable=“Device”];然后device='echo“$line”'echo$device fi完成了fedorqui,成功了,泰!但是现在当我有了输出,我如何将它们放入变量中?@Omnomnom只需说var=$(command)
。或者,在本例中,var=$(awk'/Device/{print$2}'文件)
@Omnomnom您刚刚更新了您的问题,但您所说的与您在此处的评论完全不同。请澄清一下,我明天会试试这个,但我想它会管用的,谢谢!
$ grep "^Device:" $file | cut "-d " -f2-