cut extracts fields from delimited text. It is useful for small colon-separated, comma-separated, or tab-separated records.

Program

Play the script to select a field number from a colon-delimited record.

field
cut_fields.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

record="Ada:ops:active"
field=2
value="$(printf '%s\n' "$record" | cut -d: -f "$field")"
echo "$field=$value"
#!/usr/bin/env bash

record="Ada:ops:active"
field=1
value="$(printf '%s\n' "$record" | cut -d: -f "$field")"
echo "$field=$value"
#!/usr/bin/env bash

record="Ada:ops:active"
field=3
value="$(printf '%s\n' "$record" | cut -d: -f "$field")"
echo "$field=$value"
  1. record ← Ada:ops:active

    3record="Ada:ops:active"4field=2
    values this stepAda:ops:activerecord
  2. field ← 2

    3record="Ada:ops:active"4field=25value="$(printf '%s\n' "$record" | cut -d: -f "$field")"
    values this step2field
  3. value ← ops

    4field=25value="$(printf '%s\n' "$record" | cut -d: -f "$field")"6echo "$field=$value"
    values this stepopsvalue2field
  4. echo "$field=$value"

    5value="$(printf '%s\n' "$record" | cut -d: -f "$field")"6echo "$field=$value"
    output2=ops
    values this step2fieldopsvalue
  1. record ← Ada:ops:active

    3record="Ada:ops:active"4field=1
    values this stepAda:ops:activerecord
  2. field ← 1

    3record="Ada:ops:active"4field=15value="$(printf '%s\n' "$record" | cut -d: -f "$field")"
    values this step1field
  3. value ← Ada

    4field=15value="$(printf '%s\n' "$record" | cut -d: -f "$field")"6echo "$field=$value"
    values this stepAdavalue1field
  4. echo "$field=$value"

    5value="$(printf '%s\n' "$record" | cut -d: -f "$field")"6echo "$field=$value"
    output1=Ada
    values this step1fieldAdavalue
  1. record ← Ada:ops:active

    3record="Ada:ops:active"4field=3
    values this stepAda:ops:activerecord
  2. field ← 3

    3record="Ada:ops:active"4field=35value="$(printf '%s\n' "$record" | cut -d: -f "$field")"
    values this step3field
  3. value ← active

    4field=35value="$(printf '%s\n' "$record" | cut -d: -f "$field")"6echo "$field=$value"
    values this stepactivevalue3field
  4. echo "$field=$value"

    5value="$(printf '%s\n' "$record" | cut -d: -f "$field")"6echo "$field=$value"
    output3=active
    values this step3fieldactivevalue

Follow the Fields

  1. record starts as Ada:ops:active.
  2. The colon : splits the record into three fields.
  3. field=2 asks cut for the second field.
  4. The selected value is ops.
  5. The script prints 2=ops. | field number | field value | default? | | --- | --- | --- | | 1 | Ada | no | | 2 | ops | yes | | 3 | active | no |
delimiter `-d:` tells `cut` that colon separates fields.
field number `-f` chooses which delimited field to print.
text record Simple delimited records are common in shell scripts and config files.

Exercise: cut_fields.sh

Reproduce 2=ops, then change field to the pinned variants 1 and 3 and predict 1=Ada and 3=active.