Bash逐行读取文件并将值附加到特定变量中。

huangapple go评论96阅读模式
英文:

Bash read file line by line and append the value to a specific variable

问题

我正在尝试逐行读取文件并在对变量进行一些更改后将每行的值添加到变量中。目前我正在使用以下代码-

  1. COM="Something i"
  2. while IFS= read -r line || [ -n "$line" ];
  3. do
  4. LINE="Line${line/=/,}End"
  5. COM="$COM$LINE"
  6. done < Vars
  7. COM="$COM done"
  8. echo "Vars" | piping_into_some_other_application

文件Vars的内容-

  1. VAL=something
  2. VAL2=somethingelse
  3. VAL3=some
  4. VAL4=vals

最终我希望COM是-
Something iLineVAL,somethingEndLineVAL2,somethingelseEndLineVAL3,someEndLineVAL4,valsEnd done
但我得到的是-
LineVAL4,valsEnd done

英文:

I a trying to read a file line by line and add the value of each line after making some changes to a variable.
Currently I am using this-

  1. COM=&quot;Something i&quot;
  2. while IFS= read -r line || [ -n &quot;$line&quot; ];
  3. do
  4. LINE=&quot;Line${line/=/,}End&quot;
  5. COM=&quot;$COM$LINE&quot;
  6. done &lt; Vars
  7. COM=&quot;$COM done&quot;
  8. echo &quot;Vars&quot; | piping_into_some_other_application

The content of file vars-

  1. VAL=something
  2. VAL2=somethingelse
  3. VAL3=some
  4. VAL4=vals

I finally expect COM to be-
Something iLineVAL,somethingEndLineVAL2,somethingelseEndLineVAL3,someEndLineVAL4,valsEnd done
But I get-
LineVAL4,valsEnd done

答案1

得分: 2

使用您的解决方案,"$LINE"和"$COM"在每次迭代时都会被覆盖,而不是追加。

如果可用的话,您可以使用"gawk"来实现这个目标,示例如下:

  1. awk '{gsub("=",",") ; V = V "Line" $1 "End" } END { print "Something i" V "done"}' INPUTFILE | some_other_application

(您还可以使用"sed"、"perl"等方法来实现相同的功能。)

使用"bash",可以这样做:

  1. COM=""
  2. while IFS= read -r line ; do
  3. COM="${COM}Line${line/=/,}end"
  4. done < INPUTFILE
  5. echo "Something i${COM} done" | some_other_program
英文:

With Your solution $LINE and $COM gets overwritten with every iteration instead of appending.

You can do this with gawk if that is available too look this:

  1. awk &#39;{gsub(&quot;=&quot;,&quot;,&quot;) ; V = V &quot;Line&quot; $1 &quot;End&quot; } END { print &quot;Something i&quot; V &quot;done&quot;}&#39; INPUTFILE | some_other_application

(And You can do it with sed, perl etc.)

With bash it can be done like

  1. COM=&quot;&quot;
  2. while IFS= read -r line ; do
  3. COM=&quot;${COM}Line${line/=/,}end&quot;
  4. done &lt; INPUTFILE
  5. echo &quot;Something i${COM} done&quot; | some_other_program

huangapple
  • 本文由 发表于 2020年1月6日 20:56:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定