LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   line by line reading and writing in Bash (https://www.linuxquestions.org/questions/programming-9/line-by-line-reading-and-writing-in-bash-847218/)

nesrin 11-29-2010 08:33 AM

line by line reading and writing in Bash
 
Hello,
I have a text file (myfile.txt) with columns a,b,c.
123 2 23
124 2 24
125 2 22
I want to read this file line by line and for each line i want to add a 4th column (b_c_a) which will be:
2_23_123
2_24_124
2_22_125
I tried "while read line" in bash script but i could not get what i wanted.

while read line; do
a=$(awk'{print $1}' myfile.txt)
b=$(awk'{print $2}' myfile.txt)
c=$(awk'{print $3}' myfile.txt)
d=$a'_'$b'_'$c
done

this gives:
2 2 2_23 24 25_123 124 125

I would appreciate if somebody could help me.
thanks in advance.

slinx 11-29-2010 08:51 AM

Code:

awk '{printf "%s\t%s\t%s\t%s\n", $1, $2, $3, $3 "_" $2 "_" $1 }' file.txt

druuna 11-29-2010 08:52 AM

Hi,

Is this what you are looking for:
Code:

awk '{ print $0, $2"_"$3"_"$1 }' infile
Hope this helps.

gnashley 11-29-2010 11:26 AM

We seem to be doing your homework, eh? You said using bash, so this will do that:
Code:

# initilaize an empty output file
> output-file-name
# maybe 'cat /dev/null output-file-name' is easier to understand

while read a b c ; do
 echo $a $b $c $b_$c_$a >> output-file-name
done <input-file-name


nesrin 12-01-2010 08:19 AM

thanks for the help,
all three solutions are working very well.

only on this line there is a little correction:
echo $a $b $c $0b"_"$c"_"$a >> output-file-name

PS: It is not a homework, i dont even have to do this in shell. but i would like to learn a bit how shell scripting works ;)


All times are GMT -5. The time now is 08:13 PM.