2

I have the following columns:

_111_   [555]
_222_   [666]
_333_   [777]
_444_   [888]

I want to access the 111 from _111_. or 888 from [888].

How to access the fields elements with awk.

1

try this:

  awk '{gsub("_|\\[|\\]","",$0); print $1 "-" $2;}' prova.txt

awk read each line and use " " (white space) as field separator, gsub remove chars: '_' '[' ']', so $1 and $2 will contains token without undesiderable char.

This script will output:

  111-555 
  222-666 
  333-777 
  444-888

If you would access exactly _111_ and [8888] as first token and last token, try this:

  awk '{gsub("_|\\[|\\]","",$0);if (NR == 1) print $1;}END{print $2}' prova.txt

In this case the output will be:

 111
 888

Here is awk manual where you can found more details.

1

If you have those data in a file file.txt

Access 111 as,

cat file.txt | tr -d "[]_" | awk 'NR==1 {print $1}'

Access 888 as,

cat file.txt | tr -d "[]_" | awk 'NR==4 {print $2}'

about accessing the fields elements with awk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.