patrik
patrik

Reputation: 4558

How to print first or second word in a string with awk?

So I have a string which consists of two words, where I want to print the two words separately in awk (actually gawk).The string may look like this,

str="ab cd"

So I have searched the web and all I come up with is examples how to parse this from a file. However, this does not work in my case. It would be quite easy to do in perl; Something like this,

my $str="ab cd";
$str =~/(.+)\s(.+)/;
print "$1 and $2\n";

However, awk does not have this grouping. The problem is that I need to preserve the input, so split(), sub(), ... will not help. It would probaby work with match(), but this is not so pretty.

Anyone that sits with a better idea?

Sample input: str="ab cd"
Sample output: "ab and cd"

Note that the "and" is not a part of the matching, but it should be possible to print that string.

BR Patrik

Upvotes: 1

Views: 2454

Answers (4)

Ed Morton
Ed Morton

Reputation: 203229

idk what you mean by any of However, awk does not have this grouping. The problem is that I need to preserve the input, so split(), sub(), ... will not help. It would probaby work with match(), but this is not so pretty.

The gawk equivalent of the perl code in your question:

my $str="ab cd";
$str =~/(.+)\s(.+)/;
print "$1 and $2\n";

line for line, would be:

str="ab cd"
match(str,/(.+)\s(.+)/,a)
print a[1], "and", a[2]

e.g.:

awk 'BEGIN {
    str="ab cd"
    match(str,/(.+)\s(.+)/,a)
    print a[1], "and", a[2]
}'
ab and cd

I don't know if that's the best way to do whatever it is you're really trying to do though since I don't know what it is you're really trying to do!

Upvotes: 2

Cyrus
Cyrus

Reputation: 88583

Split string with a white space to an array:

awk -v string="ab cd" 'BEGIN{split(string,array," "); print array[1],"and",array[2]}'

Output:

ab and cd

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246764

gnu awk, use the 3-argument form of the match() function

awk -v str="foo bar" 'BEGIN {
    if (match(str, /^(.+)[[:space:]]+(.+)/, m)) {
        print m[1], "and", m[2]
    }
}'
foo and bar

Upvotes: 1

Tyl
Tyl

Reputation: 5252

GNU awk:

$ awk -v str="ab cd" 'BEGIN{print gensub(/(.+)\s(.+)/, "\\1 and \\2\n", 1, str)}'
ab and cd

Change to -v str="$var" if you want transfer a variable value to awk.

Upvotes: 3

Related Questions