I have 5 files basically;namely file1.txt situated each at folder A to E respectively.
I would like to extract out third column from each of these file1.txt from folder A to folder E. Also, I wanted to extract the first and second column which are common. In other words, e.g
A/file1.txt
1 1 10
B/file1.txt
1 1 20
C/file1.txt
1 1 30
D/file1.txt
1 1 40
E/file1.txt
1 1 50
I tried
dirs=(A,B,C,D,E);
files=(file1.txt);
for file in "${files[@]}";
do for dir in "${dirs[@]}";
do awk {'print $3 '} "$dir/$file" >test.txt
done
done
This only able to print out the 3rd column separately. Ultimately, I wanted to have the below output in an external file (test.txt):-
1 1 10 20 30 40 50
The file1.txt might have more than one line. The above file1.txt data is just an example.
dirs=(A,B,C,D,E);
files=(file1.txt);
for file in "${files[@]}";
do
v=$(awk '{print $1,$2}' ${dirs[1]}/$file)
for dir in "${dirs[@]}";
do
v="$v $(awk '{ print $3 }' $dir/$file)"
done
echo "$v" >> test.txt
done
I'm presuming the "1 1" on the beginning is the same in all files, and you just obtain it from the file in the first directory.
It doesnt combine the third element until the last line read from the first directory's file.
I modified to be something like below:-
dirs=(A B C D E);
files=(file1.txt);
for file in "${files[@]}";
do
v=$(awk '{print $1,$2}' ${dirs[1]}/$file)
for dir in "${dirs[@]}";
do
w=$(awk '{print $5 }' $dir/$file)
done
echo "$v $w" >> ../test.txt
done
But its not working too, Basically i wanted to have 1 1 20(from dir A) 30(from dir B) 40 (from dir C) and 50(from dir D) corresponded with respect to each line.
Thanks for the reply. I havent try the suggested solution but I am thinking how is that possible if i have about 30 files to perform the above operation.
Is that possible the first solution suggested by Annihilannic to be tweaked ?
for dir in A B C D E
do
echo $dir/file1.txt
done |
xargs paste |
awk '{out = $1 OFS $2; for (i=3; i<=NF; i+=3) out = out OFS $i; print out}'
Execution (step by step):
> for dir in A B C D E
do
echo $dir/file1.txt
done
A/file1.txt
B/file1.txt
C/file1.txt
D/file1.txt
E/file1.txt
>
> for dir in A B C D E
do
echo $dir/file1.txt
done |
xargs echo paste # echo for debug purpose
paste A/file1.txt B/file1.txt C/file1.txt D/file1.txt E/file1.txt
>
> for dir in A B C D E
do
echo $dir/file1.txt
done |
xargs paste
1 1 A11 1 1 B11 1 1 C11 1 1 D11 1 1 E11
1 2 A12 1 2 B12 1 2 C12 1 2 D12 1 2 E12
>
> for dir in A B C D E
do
echo $dir/file1.txt
done |
xargs paste |
awk '{out = $1 OFS $2; for (i=3; i<=NF; i+=3) out = out OFS $i; print out}'
1 1 A11 B11 C11 D11 E11
1 2 A12 B12 C12 D12 E12
>