Hello,
How to print the field separator in awk? please see the following code:
cat a.txt
a 1s 2s 3s 4s
b 2s 4s
[river@localhost Desktop]$ awk 'BEGIN{FS==" "} {print $2 $3 }' te
1s2s
2s4s
I want to get the following output :
1s 2s
2s 4s
How to realize this ?
[river@localhost Desktop]$ cat te
a 1s,,2s 3s 4s
b 2s 4s
[river@localhost Desktop]$ awk 'BEGIN{ FS = "[,| ]" } {print $2 $3 }' te
1s
2s
[river@localhost Desktop]$
I want to get the following result:
1s,,2s
2s 4s
How to realize it ?
yazu
2
There is OFS - output field separator in awk. Either change it in BEGIN block, or add FS manually:
{print $1 FS $2}
However ,
{print $1 FS $2}
I get the following :
[river@localhost Desktop]$ awk ' {print $2 FS $3 }' te
1s,,2s 3s
2s 4s !!only one space
[river@localhost Desktop]$
In origin file, the content between "2s" and "4s" is 4 spaces, but it only print 1 space.
and I need to specify FS to be "," or " ".
Adjacent characters will be threaded as multiple field separators.
When FS=","
, a,,b
will be interpreted as a null b
.
It would be easy with Perl:
% cat infile
a 1s,,2s 3s 4s
b 2s 4s
% perl -nle'
print +(split /\s(?!\s)/)[1,2]
' infile
1s,,2s 3s
2s 4s
Oh, sorry, I decide not to use perl, thanks.
Why not Perl?
Which operating system and awk version are you using?
I am using fedora 15 , bash environment.
yazu
8
sed -r 's/^[^ ]+ +([^ ]+ +[^ ]+).*$/\1/' INPUTFILE
Can awk record the match result? FS==" " ,
2s 4s
so between 2s and 4s exists 4 spaces, the the match results is 4 spaces.
yazu
10
gawk 4.0 can but
It's just not a right tool for you needs. You can do it in awk with a hand parsing using substr but this is not worth it.
I have find a article, a chapter shows "Remembering patterns with \(, \) and \1" , does awk support it ?
GNU awk supports backreferences with the gensub and match string builtin functions:
$ awk 'BEGIN {
s="a b"
print "gensub:", gensub(/(.+) (.+)/, "\\2 \\1", "g", s)
match(s, /(.+) (.+)/, a)
print "match:", a[2], a[1]
}'
gensub: b a
match: b a