context_free - Linux


Overview

context_free is a command-line tool for context-free manipulation of text files. It provides powerful editing capabilities based on regular expressions and context-dependent rules. It can be utilized for various text processing tasks, such as reformatting text, stripping or extracting specific content, and data validation.

Syntax

context_free [options] FILE [rules...]

Options/Flags

  • -i: Case-insensitive matching
  • -n: Do not apply rules to input
  • -o FILENAME: Write output to FILENAME
  • -p: Print matched text only
  • -s SEP: Use SEP as the separator between matches (default is newline)
  • -v: Verbose output
  • –help: Display help information
  • –version: Display version information

Examples

Replace all occurrences of "search" with "replace":

context_free -s " " FILE s/search/replace/g

Extract phone numbers from a text file:

context_free FILE r/([0-9]{3})[ -]([0-9]{3})[ -]([0-9]{4})/p \1-\2-\3

Filter data based on multiple conditions:

context_free -p FILE r/^(John)/(?=\s.+@example\.com)/m

Common Issues

  • Invalid regular expression syntax: Ensure your regular expressions follow proper syntax.
  • No matching rules found: Check if your rules match the desired text patterns.
  • Inconsistent output: Verify the use of the -p option to avoid printing unnecessary text.

Integration

Combine with grep:

grep TERM | context_free r/.*TERM.*/p

Use as a subroutine in scripts:

#!/bin/bash
rules=(
  s/old/new/g
  r/pattern/p
)
context_free -i $1 "${rules[@]}"

Related Commands

  • sed: Stream editor
  • awk: Pattern scanning and processing language
  • grep: Search for patterns in text files