EverLearner
EverLearner

Reputation: 135

Print part of a comma-separated field using AWK

I have a line containing this string:

$DLOAD , 123 , Loadcase name=SUBCASE_1

I am trying to only print SUBCASE_1. Here is my code, but I get a syntax error.

awk -F, '{n=split($3,a,"="); a[n]} {printf(a[1]}' myfile

How can I fix this?

Upvotes: 1

Views: 685

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133428

1st solution: In case you want only to get last field(which contains = in it) then with your shown samples please try following

awk -F',[[:space:]]+|=' '{print $NF}' Input_file


2nd solution: OR in case you want to get specifically 3rd field's value after = then try following awk code please. Simply making comma followed by space(s) as field separator and in main program splitting 3rd field storing values into arr array, then printing 2nd item value of arr array.

awk -F',[[:space:]]+' '{split($3,arr,"=");print arr[2]}' Input_file

Upvotes: 4

David C. Rankin
David C. Rankin

Reputation: 84531

Possibly the shortest solution would be:

awk -F= '{print $NF}' file

Where you simply use '=' as the field-separator and then print the last field.

Example Use/Output

Using your sample into in a heredoc with the sigil quoted to prevent expansion of $DLOAD, you would have:

$ awk -F= '{print $NF}' << 'eof'
> $DLOAD , 123 , Loadcase name=SUBCASE_1
> eof
SUBCASE_1

(of course in this case it probably doesn't matter whether $DLOAD was expanded or not, but for completeness, in case $DLOAD included another '=' ...)

Upvotes: 4

Related Questions