简体   繁体   English

如何将文件中行的最后一个字段附加到powershell cli上的变量?

[英]How to append last field of a line in a file to a variable on powershell cli?

Here is my file hello.txt : 这是我的文件hello.txt

"ReceiptHandle" = "hellomyfriend==++" “ ReceiptHandle” =“ hellomyfriend == ++”

I would like to append only the last field of a line to a variable: 我只想将一行的最后一个字段附加到变量中:

$friend = hellomyfriend==++

Assuming that is all that's in your hello.txt file. 假设这就是您的hello.txt文件中的全部内容。 The following would assign "" to your $friend variable... 以下将为您的$ friend变量分配“”。

$myhash = (gc 'hello.txt') -replace """","" | ConvertFrom-StringData
$friend = $myhash["ReceiptHandle"]

ConvertFrom-StringData makes this easy because your text is already in "something = value" format. ConvertFrom-StringData使此操作变得容易,因为您的文本已经采用“某物=值”格式。

So what's going on here? 那么这是怎么回事? First, 第一,

gc 'hello.txt' gc'hello.txt'

is getting the contents of your file. 正在获取文件的内容。 I encapsulate it in () so that i can use.. 我将其封装在()中,以便可以使用。

-replace """","" -替换“”“”,“”

.. to get rid of the surrounding double-quotes. ..删除周围的双引号。 That's piped into ConvertFrom-StringData, which converts the string into a named key/value pair [hashtable]. 这被传递到ConvertFrom-StringData中,后者将字符串转换为命名键/值对[hashtable]。 From there, I can access the second part by interrogating the hashtable. 从那里,我可以通过查询哈希表来访问第二部分。

Alternatively, you could put this all on one line... 或者,您可以将所有内容放在一行上...

(gc 'hello.txt') -replace """","" | ConvertFrom-StringData | %{$friend = $_["ReceiptHandle"]} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM