Reputation: 23
I am trying to extract the second column out of 22 different files. I get a correct output when working on a single file but when in a loop, in each file it concatenates in series the 2 column of several different files in one. Can anybody please help me.
for i in f*
do
awk '{print $2}' f* > a_$i
done
Upvotes: 2
Views: 80
Reputation: 113814
This does what you want:
awk '{print $2 >"a_"FILENAME}' f*
For every file starting with the letter f
, this writes its second columns to a new file that starts with a_
.
The output files have the same number of rows as the input but the output has only the second column.
Note that the above works because >
means something somewhat different in awk
than it does in shell.
Suppose that we have a series of files like:
$ cat f1
One 1
One 11
Now, let's run the awk
command:
$ awk '{print $2 >"a_"FILENAME}' f*
When this is done, there are a series of a_*
files in the directory, such as:
$ cat a_f1
1
11
Upvotes: 1
Reputation: 174696
Change your command like,
for i in f*
do
awk '{print $2}' "$i" > "a_$i"
done
One-liner,
for i in f*; do awk '{print $2}' "$i" > "a_$i"; done
You need to replace f*
in your awk command with $i
which stores the current file name.
Upvotes: 2