0

I have a .txt file with the following content:

"aaa@bbb.de"

Now, I want to paste these strings with the help of my while loop to the stdout, in such a way that echo should write "text aaa@bbb.de text"

while read line;
do 
    echo "text $line text"
done <./textfile.txt

But all I get is: text"aaa@bbb.de"

--> The whitespaces are missing and the text after $line as well.

If I change it as below

while read line;
do 
     echo "text\ $line text"
done <./textfile.txt

I get text "aaa@bbb.de"

--> After the first text, there is a whitespace but after aaa@bbb.de, there is no text.

AdminBee
  • 22,803
cd4user
  • 33
  • By using the same string, text at each end of your echo statement you can't tell when you see the string text in the output if it's the string from before $line or the same string from after it. Given that, when you say The whitespaces are missing and the text after $line as well. you're misdiagnosing the problem - it's not the text after $line that's missing, it's the text before it that's missing as it's being overwritten by the text after it. Change echo "text $line text" to echo "foo $line bar" and it'll be much easier for you to see what's really happening. – Ed Morton Jan 13 '22 at 14:18
  • General rule of thumb when writing debugging print statements - don't use the same string in multiple locations in those print statements or you won't be able to tell where that string came from when you see it in the output and so will be missing useful information. – Ed Morton Jan 13 '22 at 14:23

2 Answers2

2

Since using shell loops for text processing is considered bad practice, I would recommend a different approach that uses dedicated text-processing tools. In particular, awk comes to mind:

awk '{printf "text %s text\n",$0}' textfile.txt 

This will use Awk's builtin printf function (using the same formatting syntax as the well-known C function) to print the entire current line (represented by $0) enclosed by text on both ends.

As for why your approach didn't work: Since you confirmed that the text file was edited on a Windows-based machine, this means that the line endings are in a format the Linux doesn't correctly interpret. In that case, run the file through dos2unix, as in

dos2unix textfile.txt

The resulting file should be processed correctly.

AdminBee
  • 22,803
1

Introducing myself to perl so feel free to learn with me:

perl -ne ' s/\n|"//g ; print "\"text $_ text2\"\n" ' infile.txt
  • read file line-by-line -n
  • execute the inline script -e
  • remove all newline and quotes from input line s/\n|"//g
  • and print string in desired format
  • $_ is the variable for the input and its processed form, respectively
FelixJN
  • 13,566