With bash
:
$ while IFS=@ read -r col1 col2 col3 col4; do
echo $col3
done <<< '@field1@field2@field3@field4'
field2
Another way with awk
$ awk '{split($0,ary,/@/); print ary[3]}' <<< '@field1@field2@field3@field4'
field2
문제
I've got a file calling "file" where there are some fields separated with a separator. The structure of the file is:
@field1@field2@field3@field4
With awk i've extracted the fields without separators.
vr=$file;
sep_mx=`echo $vr | awk '{
n=split($0,x,"@");
print n
}'`
echo $sep_mx
## here the number of substring produced is calc.
while ((i<=$max));
do
# would print individual substring one at a
# time as the counter increases.
echo $vr | awk -v er=$i '{
n=split($0,x,"@"); print x[er]
}'
((i+=1))
done
The output is:
field1
field2
field3
field4
If i want to extract only the second field from the code i've just posted how can i do it? Thanks
해결책 2
With bash
:
$ while IFS=@ read -r col1 col2 col3 col4; do
echo $col3
done <<< '@field1@field2@field3@field4'
field2
Another way with awk
$ awk '{split($0,ary,/@/); print ary[3]}' <<< '@field1@field2@field3@field4'
field2
다른 팁
This should make it:
awk -F@ '{print $3}' file
In general, try to use -F
. It means "field separator" and makes your life easier, with no needs to split, substr and things like that.
$ awk -F@ '{print $3}' file
field2
The GNU sed invocation
sed -r 's/\W\w+\W(\w+).*/\1/' file
outputs
field2
Your code doesn't make sense. If want to convert
@field1@field2@field3@field4
to
field1
field2
field3
field4
then all you need is this (or any of various other simple solutions):
$ cat file
@field1@field2@field3@field4
$
$ gawk -v RS='[@\n]' 'NR>1' file
field1
field2
field3
field4
If you want to print text "field3" then it's simply:
$ gawk -v RS='[@\n]' 'NR==4' file
field3
The record number is 4 instead of 3 because your file starts with "@" so there's an empty record before "field1".
If you tell us what you're really trying to do we can help you, so far you seem to be going down the wrong path.