0

I know this question appears rather frequently, but I cannot seem to find a solution on importing a .txt file line by line to another .txt with the While Read command:

line="input.txt"

while read -r line; do
  printf '%s\n' "$line"
done < outputfile.txt

I tried different alternatives, tried them all as variables, using the variables with their directories, tried cat on the input file, use of echo and printf but to no avail. Thanks in advance for any and all advance!

  • Can you explain what’s going wrong - that is, what is happening, and how is that different from what you want to happen? Also, exactly what do you mean by “import”? – Gordon Davisson Nov 21 '18 at 17:32
  • I want it to read the input txt file into the output txt file line by line, though this code runs without errors, nothing gets inputted into the outputfile and it remains blank – Daniel Jameson Nov 21 '18 at 17:40
  • 2
    you are using outputfile.txt as input in your example, < outputfile.txt means it takes data from that file, not put it in that file, it assigns $line to line it gets from output.txt file, see answer by Mike Q below, you don't need line="input.txt" at all, just put < input.txt instead of outputfile.txt and output the contents of loop to outputfile.txt – ralz Nov 21 '18 at 17:43
  • 1
    `while read -r line; do printf '%s\n' "$line"; done < inputfile.txt > outputfile.txt` – William Pursell Nov 21 '18 at 17:55
  • Thank you William as that code has sorted it and thanks to everyone else, you would get votes but I don't think I got that option yet – Daniel Jameson Nov 22 '18 at 18:13

1 Answers1

2

I think you are just trying to combine files ?

cat input.txt >> outputfile.txt 

Not suggesting this but as an FYI :

file="input.txt"
while IFS= read -r line ;do
    echo "${line}" >> outputfile.txt 
done < "${file}"
Mike Q
  • 6,716
  • 5
  • 55
  • 62
  • 3
    Somehow your code has "smart quotes" in it -- `“` where it should be `"`. Consequently, it won't work if copied-and-pasted. (BTW, speaking of quotes, consider `<"$file"`, with double quotes around the expansion, to avoid bugs with shell versions that don't suppress string-splitting on redirection -- unfortunately, this includes versions of bash still in use today, which can cause surprising "ambiguous redirect" errors). – Charles Duffy Nov 21 '18 at 18:13
  • 2
    Or, `while IFS= read -r line; do echo "$line"; done < input >> output` with the output redirection outside the loop. – glenn jackman Nov 21 '18 at 19:50