Reading Complete Line in 'For' Loop with Spaces, Tabs with Multiple Input Files

Use Bash to read line by line and keep space

IFS=''
cat test.file |
while read data
do
echo "$data"
done

I realize you might have simplified the example from something that really needed a pipeline, but before someone else says it:

IFS=''
while read data; do
echo "$data"
done < test.file

Why can scanf read multiple inputs in a line with a for loop?

When you type in some numbers on your console and hit ENTER, you are providing an input stream to your code via stdin. The entire contents of what you type in are kept in that input stream. So if you type

2 4 6 8

and hit enter, the input stream contains:2 4 6 8

Now, each of your scanfs is only reading (and removing) a single integer from that input stream, so after a single scanf, the stdin input stream now contains: 4 6 8

The extra input is not discarded, it is still available in the input stream, so your next scanf can come along and grab the next integer from the stream, and the next, and the next.....until the data in the input stream is exhausted.

How to loop over a file with space/tab

Try the following code:

while read line; do
echo "$line" | cut -d " " -f1
# ├────┘
# |
# └ Split at empty space
done <sample.txt

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

Read a line of input including space-delimited strings and display them as a single complete line using getline

While I don't agree with the approach you are taking here, here is how I would solve your current problem:

Since the name in test.txt is split across multiple lines, you have to keep using getline until there is no more input. Thus, you should use the following instead of a single getline statement:

string input;
while (getline(cin, input))
{
name += input;
}

This reads through every single line in the file, and adds it to the name, while ignoring whitespace (There is none anyway) and line breaks (Which signify the end of a line).

Output:

$./hello < test.txt
What is your name?
Hello JohnDoe!

Adding a space between the first and last name should be trivial, but I am going off the fact that you said whitespace should be ignored.



Related Topics



Leave a reply



Submit