Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hello All,
The script need to read a file, which contains such as follows:
Mary age22 address1
Peter age33 address2
eofthen all data put into variable
Output like : name = Mary
age = age22
address = address1name = Peter
age = age33
address = address2

If you want output formatting, David gave you a solution for that. If you need to load the fields into variables so that you can work with the variables, the script below provides an example:
while read name age addr other
do
# echo name=$name age=$age addr=$addr
printf "name=%-10s age=%-6s addr=%s\n" $name $age $addr
done < infile

Thanks.
I have another question.
If I want to get exactly field size of name, age and address. What should I do?
for example: input name = char 5
age = char 2
addr = char 40
while true
$read name | cut -d -f,5
$read age | cut -d -f,2
$read addr | cut -d -f ,40
do
# echo name=$name age=$age addr=$addr
printf "name=%-10s age=%-6s addr=%s\n" $name $age $addr
done < infileCan I do like that?
Thanks and Regards,
Apple

If you are asking how to pull variables from each line of your file based upon fixed column positions, then I believe you have the general idea of it. In the ksh script below, the while-loop reads each line of infile into the $line variable, then I show two different ways to split up $line based upon fixed column positions.
IFS=""
while read line
doname=$(expr "$line" : "\(.....\)")
age=$(expr "$line" : ".....\(..\)")
addr=$(expr "$line" : ".......\(.*\)")#name=$(echo $line | cut -c1-5)
#age=$(echo $line | cut -c6-7)
#addr=$(echo $line | cut -c8-)printf "name=%-6s age=%-3s addr=%s\n" $name $age $addr
done < infile

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |