Need help with ksh

I have the following file:

one two three four
man women
yes no place togo
bad sleep

I need to move all lines that have only two words(columns) in a separate file and the rest in a separate file...

I used :

for $linecont in $(cat $filename); do
echo $linecont > temp
line1='cat temp|awk -F ' ' '{print $3;}'`
if [$line1 = ""] then
echo $linecont > file2
else
echo $linecont > file4
fi

This did not work for me ...

Please help.
TIA

try:

awk 'NF==2{print > "file2"; next}{print > "file4"}' $filename

Or using the shell:

>file2
>file4
while read line
do
   set -- $line
   if [ $# -eq 2 ]
   then
      echo "$line" >> file2
   else
      echo "$line" >> file4
   fi
done < $filename
1 Like

I think you can use below one to get required output.

awk '{if(NF==2) print $0}' <file_name>

awk '{if(NF!=2) print $0}' <file_name>

Regards,
Srikanth

1 Like

Thanks Chubler_XL!
thanks Srikanth.

Any reason why my code did not work?
The reason why I used my method:
My goal is to create two files from file4:

File5:

select one from two;
select yes from no;

File6:

select three from four;
select place from togo;

TIA

There are quite a few issues with the your existing code.

Avoid using cat when commands accept a file name, or you can direct file straight to them. This didn't cause anything to fail to do what you wanted, but is poor form and wastes processing power invoking the cat executable.

echo $linecont > temp
This strips any multiple white space from output you should quote the line to protect spaces like echo "$linecont" > temp

if [$line1 = ""] then
You need to quote $line1 here otherwise if it's blank the file expression will complain about = "" is not valid syntax.

echo $linecont > file2
This will not append to the file and will just keep the list line found use ">>" to append but you must empty/remove any old files at start of your program.

1 Like

Hey,

Could you please read you file using while loop, below code is working.

while read linecont
do
line1=`echo $linecont|awk -F ' ' '{print $3;}'`
if [ "$line1" = "" ] 
then
echo $linecont >> file2
else
echo $linecont >> file4
fi
done<$filename

Regards,
Srikanth

1 Like

Thanks for your reply:
when I used your notation:

awk 'NF==2{print > $file1; next}{print > $file2}' $filename

it does not work with file variables, what I do wrong?

Best idea is to pass variables into awk with -v like this:

awk -v F1="$file1" -v F2="$file2" 'NF==2{print > F1; next}{print > F2}' $filename