LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   cat command space problem with awk in for loop. (https://www.linuxquestions.org/questions/programming-9/cat-command-space-problem-with-awk-in-for-loop-733602/)

shan_nathan 06-17-2009 08:35 AM

cat command space problem with awk in for loop.
 
Dear all,

I am trying to echo some value using awk, and for reading the file i am using cat command. If there no space in the file content then the following script result correctly.
------------------------------------------------
console: # cat 1
one;two;three;
four;five;six;

console: # cat 2
for J in `cat 1`
do
A=`echo $J | awk -F ';' '{ print $1 }'`
echo $A
done

console: # ./2
one
four
console: #
--------------------------------------------------
In case any space is there in the file 1 then i am facing the problem in the output value .
-------------------------------------------------
console: # cat 1
o ne;two;three;
four;five;six;

console: # cat 2

for J in `cat 1`
do
A=`echo $J | awk -F ';' '{ print $1 }'`
echo $A
done

console: # ./2
o
ne
four
console: #
--------------------------------------------------

Can some one tell me how to omit that space.

Thanks.

colucix 06-17-2009 08:51 AM

The problem is in the statement:
Code:

for J in `cat 1`
because the shell uses space as field separator, so that the loop is executed three times on the following strings:
1) o
2) ne;two;three;
3) four;five;six;

Anyway, you don't really need such a loop, since awk can parse the content of a file line after line. You can simply do
Code:

awk -F";" '{print $1}' 1
If you want to remove the blank space, just do something like this:
Code:

awk -F";" '{print gensub(/ /,"","g",$1)}' 1
The gensub statement just replace any space in the first field with the null string.

colucix 06-17-2009 08:58 AM

Regarding the way the shell splits lines, you have to consider the IFS environment variable. From the bash man page:
Code:

IFS    The Internal Field Separator that is used for word splitting after expansion and to
      split lines into words with the read builtin command. The default value is
      "<space><tab><newline>".

You can temporarily change the value of IFS in a script to avoid behaviors like that shown above. For example:
Code:

#!/bin/bash
OLD_IFS=$IFS
IFS=$(echo)
for J in `cat 1`
do
  A=`echo $J | awk -F ';' '{ print $1 }'`
  echo $A
done
IFS=$OLD_IFS


kike_coello 06-18-2009 05:51 AM

why don't you try the tr command?

file_1=`cat 1 | tr -d ' '` # this removes spaces from your file

then use file_1 as your new temporary file like this:

cat $file_1

instead of:

cat 1


All times are GMT -5. The time now is 04:57 AM.