【问题标题】:How can I store a string in textfile1 into a variable in textfile2?如何将 textfile1 中的字符串存储到 textfile2 中的变量中?
【发布时间】:2020-08-23 16:52:02
【问题描述】:

假设我们有两个文件 text1.txt 和 text2.txt

text 1 存储数据并读取如下内容:

line1: "peter.petterson@xyz.com passwordtext"
line2: "anne.anneson@xyz.com passwordtext"

文件中不包含“line1:”和“”。我把它们放在这里只是为了表明我有两条看起来相似的线。

现在我要做的是在 textfile2 中创建变量“name”、“surname”、“password”和“email”。

【问题讨论】:

  • 在 bash 中使用 readawk 也很适合这个。在 ws 上拆分并分配给一个变量。发布一些代码,如果您遇到困难,我们很乐意为您提供帮助。祝你好运!
  • 所以你希望 text2.txt 包含name=Peter surname=Peterson email=peterpeterson@gy.com?
  • 完全正确。有一个循环会有所帮助,但我想一旦我了解如何从另一个文件中获取数据,我就可以解决这个问题
  • 名字是否总是由两个单词组成?
  • line1: 和双引号 " 包含在 file1 中?

标签: linux string bash macos scripting


【解决方案1】:

你可以用awk试试这个:

awk -F '[.@ ]' '{print "name="$1"\n" "surname="$2"\n" "email="$1"."$2"@"$3"."$4"\n" "password="$5}' textfile1 > textfile2

【讨论】:

  • 不幸的是,这不是我想要的。它为每个用户创建变量。我想要一个变量。并且根据我当前读取的行,它应该调整它的值。
  • @SenorPantalones 你能分享一下预期的输出吗?请在主帖中添加 file2.txt 的预期内容
【解决方案2】:

记住部分字符串并构造你需要的东西。

sed -r 's/([^.]*).([^@]*)@([^ ]*).*/name=\1 surname=\2 email=\1.\2@\3/' text1.txt > text2.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2014-07-27
    • 2017-09-27
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多