简体   繁体   English

将文件内容附加到 bash 文件内循环中的字符串变量不起作用

[英]Appending file content to a String variable in loop within a bash file is not working

I am passing a text file to a bash while running.我在运行时将文本文件传递给 bash。 Text file has contents I want to supply to a java program as argument.文本文件包含我想作为参数提供给 java 程序的内容。 Text file has each content in a new line.文本文件的每个内容都在一个新行中。 The contents print fine within the loop but I need to create a concatenated string with all the contents to pass to java program and appending to a string variable in loop is not working.内容在循环中打印正常,但我需要创建一个连接字符串,其中包含要传递给 java 程序的所有内容,并且在循环中附加到字符串变量不起作用。 This is how the program looks like:这是程序的样子:

#!/bin/bash
args=""
for var in $(cat payments.txt)
do 
  echo "Line:$var"
  args+="$var "
done
echo "$args"

It prints:它打印:

Line: str1
Line:str2
 str2  // args should have appended values of each line but it got only last line

File looks like:文件看起来像:

str1
str2

Can anyone suggests what I am doing wrong here?谁能建议我在这里做错了什么?

Thanks谢谢

Your first echo is printing out the combination and not storing it in a new variable.您的第一个回声是打印出组合,而不是将其存储在新变量中。 Try:尝试:

#!/bin/bash
args=""
for var in $(cat payments.txt)
do 
  echo = "Line:$var" # this line prints but doesn't alter $var
  args+="Line:$var2 " #add Line: in here
done
echo "$args"

Simply use the variable in the right hand side of your assignment.只需使用赋值右侧的变量即可。 Note: for var in $(cat payments.txt) is a nice example of useless use of cat .注意: for var in $(cat payments.txt) cat使用的一个很好的例子。

#!/bin/bash
args=""
while IFS= read -r var; do
  args="$args $var"
done < payments.txt
echo "$args"

But instead of looping with bash, which is not very efficient, you could as well use a text processor like sed , for instance:但不是使用 bash 循环,这不是很有效,您还可以使用像sed这样的文本处理器,例如:

$ args=$(sed -n ':a;${s/\n/ /g;p;};N;ba' payments.txt)
$ echo "$args"
str1 str2

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

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