0

I have a structured text file test.tr, and I would like to analyze it with an AWK script, but for a special reason I want to get all numbers surrounded with underscores, for example: _0_ should become 0. This is an example of input text file: s 0.000000000 _0_ RTR

So I'm trying to use the cut command inside the AWK script as follows:

# AWK script
BEGIN{
 # initialization
 highest_node_id = 0;
}
{
    node_id = $3
    node_id = node_id | cut -d "_" -f2 | cut -d "_" -f1 ;# this line causes error 
    if (node_id > highest_node_id) {
        highest_node_id = node_id;
    }
}
END{
 #print results
}

But I get an error

awk: `analyze.awk: line 37: syntax error at or near cut`

whereas the same command works OK in a bash script.

What should I do?

3
  • 2
    You should show your whole script and a sample of the input and explain the result you want.
    – Zanna
    Sep 14, 2017 at 7:46
  • 1
    Based on your (poor) problem statement, I suspect you should be setting an appropriate multi-character separator - or using awk's built-in substr or gsub command to remove the surrounding characters instead. See GNU awk: String-Manipulation Functions Sep 14, 2017 at 9:03
  • @Zanna, steeldriver Thanks for your response, the desired modification done to the original post.
    – A. AlmasrI
    Sep 14, 2017 at 15:04

2 Answers 2

1

I finally got it to work by using substr:

tmp_node_id = $3;
node_id = substr(tmp_node_id, 2, (length(tmp_node_id) - 2));
printf ("node %s\n", node_id);
0

cut works in a bash script, but shell is shell and awk is awk. You can't use perl commands in awk scripts either.

If you want external programs inside your script, you need to use the system command, but for what you seem to be doing here, you should use the string functions of awk like substr and gensub.

1
  • @ Philippos thanks for your response, i want to use cut command to extract string surrounded with underscores, as these strings represents node id, i can't use substr because i don't know the total numbers of characters that represent the node id. Please give me an example of using system inside awk script. I try the following but it not works system("node_id | cut -d "_" -f2 | cut -d "_" -f1")
    – A. AlmasrI
    Sep 22, 2017 at 14:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .