2

I wrote the following script. I want to read a file and print as line by line but it considering space as new line. why is that?

#!/bin/bash
for i in `cat data.txt`
do
echo $i
done

Input: Saved in file name data.txt

B  FM_Server10_grp GPCBIOEMM10          Y          N               ONLINE

Output:

B
FM_Server10_grp
PCBIOEMM10
Y
N
ONLINE

Another question: How can I extract only number value like 10 from GPCBIOEMM10?

muru
  • 72,889
  • Your script isn't doing what you want it to do. backticks substitute the command's output in-place (e.g. the whole file). Also, separate questions should be separate Questions. – Jeff Schaller Dec 18 '15 at 19:16
  • The real problem here is trying to process text in a shell loop. See http://unix.stackexchange.com/q/169716/135943. Also, you don't need a script for what you're doing here, you should just run cat data.txt directly. – Wildcard Dec 18 '15 at 20:57

1 Answers1

4

for i in ... by default loops over a whitespace-delimited list of tokens, not newline-delimited list of tokens. Both space and newline are whitespace characters and are therefore considered delimiters.

Consider:

while read line; do
    echo $line
done < data.txt

read will, by default, read up until a newline and store what it reads in the given variable.

Andy Dalton
  • 13,993