Home > Software design >  Print part of a comma-separated field using AWK
Print part of a comma-separated field using AWK

Time:03-11

I have a line containing this string:

$DLOAD , 123 , Loadcase name=SUBCASE_1

I am trying to only print the SUBCASE_1. Here is my code, but get a syntax error. Can you please help?

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

CodePudding user response:

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 '=' ...)

CodePudding user response:

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
  • Related