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

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

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

问题

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

COM="Something i"

while IFS= read -r line || [ -n "$line" ];
do
   LINE="Line${line/=/,}End"
   COM="$COM$LINE"
done < Vars

COM="$COM done"

echo "Vars" | piping_into_some_other_application

文件Vars的内容-

VAL=something
VAL2=somethingelse
VAL3=some
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-

COM=&quot;Something i&quot;

while IFS= read -r line || [ -n &quot;$line&quot; ];
do
   LINE=&quot;Line${line/=/,}End&quot;
   COM=&quot;$COM$LINE&quot;
done &lt; Vars

COM=&quot;$COM done&quot;

echo &quot;Vars&quot; | piping_into_some_other_application

The content of file vars-

VAL=something
VAL2=somethingelse
VAL3=some
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"来实现这个目标,示例如下:

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

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

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

COM=""
while IFS= read -r line ; do
    COM="${COM}Line${line/=/,}end"
done < INPUTFILE
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:

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

COM=&quot;&quot;
while IFS= read -r line ; do
    COM=&quot;${COM}Line${line/=/,}end&quot;
done &lt; INPUTFILE
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:

确定