英文:
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="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
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 '{gsub("=",",") ; V = V "Line" $1 "End" } END { print "Something i" V "done"}' INPUTFILE | some_other_application
(And You can do it with sed
, perl
etc.)
With bash
it can be done like
COM=""
while IFS= read -r line ; do
COM="${COM}Line${line/=/,}end"
done < INPUTFILE
echo "Something i${COM} done" | some_other_program
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论