Skip to main content
Glama

sed_edit

Make small edits to files using sed patterns for single-line changes, pattern replacements, and simple text transformations.

Instructions

Make small edits to files using sed patterns. Efficient for single-line changes, pattern replacements, and simple text transformations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileYesPath to the file to edit
patternYesSed pattern (e.g., "s/old/new/g" for substitution)
backupNoCreate backup file before editing
previewNoPreview changes without modifying file

Implementation Reference

  • The handler for the 'sed_edit' tool. Parses arguments, checks file existence, constructs and executes a Perl command using the provided sed-like pattern for editing the file. Supports preview mode (with diff) and backup creation. Returns success message or preview output.
    case 'sed_edit': {
      const { file, pattern, backup = true, preview = false } = args;
      
      // Check if file exists
      if (!existsSync(file)) {
        throw new Error(`File not found: ${file}`);
      }
      
      // Build sed command - use perl for better compatibility
      let sedCmd;
      if (preview) {
        // For preview, create a temp copy and diff
        const tempFile = `${file}.preview.tmp`;
        await execAsync(`rm -f .bak; cp '${file}' '${tempFile}'`);
        
        // Apply change to temp file
        sedCmd = `perl -i -pe '${pattern}' '${tempFile}' && diff -u '${file}' '${tempFile}' | head -50; rm -f '${tempFile}'`;
      } else {
        // Use perl for actual edits (more portable than sed)
        const backupExt = backup ? '.bak' : '';
        sedCmd = `perl -i${backupExt} -pe '${pattern}' '${file}'`;
      }
      
      const { stdout, stderr } = await execAsync(sedCmd);
      
      if (stderr) {
        throw new Error(`Sed error: ${stderr}`);
      }
      
      return {
        content: [
          {
            type: 'text',
            text: preview ? 
              `Preview of changes:\n${stdout || 'No changes would be made'}` :
              `Successfully edited ${file}${backup ? ' (backup created as .bak)' : ''}`
          }
        ]
      };
    }
  • The input schema definition for the sed_edit tool, defining parameters: file (required string), pattern (required string), backup (optional boolean, default true), preview (optional boolean, default false).
    {
      name: 'sed_edit',
      description: 'Make small edits to files using sed patterns. Efficient for single-line changes, pattern replacements, and simple text transformations.',
      inputSchema: {
        type: 'object',
        properties: {
          file: {
            type: 'string',
            description: 'Path to the file to edit'
          },
          pattern: {
            type: 'string',
            description: 'Sed pattern (e.g., "s/old/new/g" for substitution)'
          },
          backup: {
            type: 'boolean',
            default: true,
            description: 'Create backup file before editing'
          },
          preview: {
            type: 'boolean',
            default: false,
            description: 'Preview changes without modifying file'
          }
        },
        required: ['file', 'pattern']
      }
    },
  • src/index.ts:36-280 (registration)
    The registration of all tools including sed_edit via the ListToolsRequestSchema handler, which returns the list of available tools with their schemas.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'sed_edit',
            description: 'Make small edits to files using sed patterns. Efficient for single-line changes, pattern replacements, and simple text transformations.',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'Path to the file to edit'
                },
                pattern: {
                  type: 'string',
                  description: 'Sed pattern (e.g., "s/old/new/g" for substitution)'
                },
                backup: {
                  type: 'boolean',
                  default: true,
                  description: 'Create backup file before editing'
                },
                preview: {
                  type: 'boolean',
                  default: false,
                  description: 'Preview changes without modifying file'
                }
              },
              required: ['file', 'pattern']
            }
          },
          {
            name: 'sed_multifile',
            description: 'Apply sed pattern to multiple files matching a glob pattern',
            inputSchema: {
              type: 'object',
              properties: {
                pattern: {
                  type: 'string',
                  description: 'Sed pattern to apply'
                },
                filePattern: {
                  type: 'string',
                  description: 'File glob pattern (e.g., "*.ts", "src/**/*.js")'
                },
                directory: {
                  type: 'string',
                  default: '.',
                  description: 'Starting directory for search'
                },
                backup: {
                  type: 'boolean',
                  default: true,
                  description: 'Create backup files'
                }
              },
              required: ['pattern', 'filePattern']
            }
          },
          {
            name: 'awk_process',
            description: 'Process files using AWK for more complex operations like column manipulation, calculations, or conditional processing',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'Input file path'
                },
                script: {
                  type: 'string',
                  description: 'AWK script to execute'
                },
                outputFile: {
                  type: 'string',
                  description: 'Output file path (optional, defaults to stdout)'
                }
              },
              required: ['file', 'script']
            }
          },
          {
            name: 'quick_replace',
            description: 'Simple find and replace across a file without regex',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'File to edit'
                },
                find: {
                  type: 'string',
                  description: 'Text to find (literal, not regex)'
                },
                replace: {
                  type: 'string',
                  description: 'Text to replace with'
                },
                all: {
                  type: 'boolean',
                  default: true,
                  description: 'Replace all occurrences (false = first only)'
                }
              },
              required: ['file', 'find', 'replace']
            }
          },
          {
            name: 'line_edit',
            description: 'Edit specific lines by number or range',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'File to edit'
                },
                lineNumber: {
                  type: 'number',
                  description: 'Line number to edit (1-based)'
                },
                lineRange: {
                  type: 'string',
                  description: 'Line range (e.g., "10,20" or "5,$")'
                },
                action: {
                  type: 'string',
                  enum: ['replace', 'delete', 'insert_after', 'insert_before'],
                  description: 'Action to perform'
                },
                content: {
                  type: 'string',
                  description: 'New content (for replace/insert actions)'
                }
              },
              required: ['file', 'action']
            }
          },
          {
            name: 'perl_edit',
            description: 'Edit files using Perl one-liners (more powerful than sed, better cross-platform support)',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'File to edit'
                },
                script: {
                  type: 'string', 
                  description: 'Perl script (e.g., "s/old/new/g" or "$_ = uc" for uppercase)'
                },
                backup: {
                  type: 'boolean',
                  default: true,
                  description: 'Create backup file'
                },
                multiline: {
                  type: 'boolean',
                  default: false,
                  description: 'Enable multiline mode (-0777)'
                }
              },
              required: ['file', 'script']
            }
          },
          {
            name: 'diff_preview', 
            description: 'Preview what changes would be made by showing a diff',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'File to preview changes for'
                },
                command: {
                  type: 'string',
                  description: 'Command that would make changes (e.g., "s/old/new/g")'
                },
                tool: {
                  type: 'string',
                  enum: ['sed', 'perl', 'awk'],
                  default: 'perl',
                  description: 'Which tool to use for the preview'
                }
              },
              required: ['file', 'command']
            }
          },
          {
            name: 'restore_backup',
            description: 'Restore a file from its most recent backup (.bak)',
            inputSchema: {
              type: 'object',
              properties: {
                file: {
                  type: 'string',
                  description: 'File to restore from backup'
                },
                keepBackup: {
                  type: 'boolean',
                  default: true,
                  description: 'Keep the backup file after restoring'
                }
              },
              required: ['file']
            }
          },
          {
            name: 'list_backups',
            description: 'List all backup files in a directory',
            inputSchema: {
              type: 'object',
              properties: {
                directory: {
                  type: 'string',
                  default: '.',
                  description: 'Directory to search for backup files'
                },
                pattern: {
                  type: 'string',
                  default: '*.bak',
                  description: 'Backup file pattern'
                }
              }
            }
          },
          {
            name: 'help',
            description: 'Get detailed help and examples for smalledit tools',
            inputSchema: {
              type: 'object',
              properties: {
                tool: {
                  type: 'string',
                  description: 'Tool name for help (e.g., "sed_edit", "perl_edit") or "all" for overview'
                }
              }
            }
          }
        ]
      };
    });
  • Help content and examples for the sed_edit tool, stored in helpContent object.
      sed_edit: `sed_edit - Pattern-based file editing
    ===================================
    Uses perl backend for cross-platform compatibility.
    
    Examples:
      // Simple replacement
      sed_edit({ file: "config.json", pattern: "s/localhost/production/g" })
      
      // Delete lines containing pattern
      sed_edit({ file: "app.js", pattern: "$_ = '' if /console\\.log/" })
      
      // Preview changes first
      sed_edit({ file: "test.txt", pattern: "s/old/new/g", preview: true })
      
      // Edit without backup
      sed_edit({ file: "temp.txt", pattern: "s/a/b/g", backup: false })
    
    Note: Actually uses perl internally for better compatibility.
    
    WHEN NOT TO USE:
    - Multi-line replacements
    - Complex code modifications  
    - JSON/YAML structure changes
    → Use filesystem:edit_file instead!
    `,
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions efficiency characteristics but doesn't address critical behavioral aspects like whether this is a destructive operation (though implied by 'edits'), error handling, permission requirements, or side effects. The description adds minimal behavioral context beyond the basic operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly concise with two sentences that each earn their place. The first sentence establishes the core functionality, and the second provides valuable context about appropriate use cases. There's zero wasted language or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 4 parameters, 100% schema coverage, but no annotations or output schema, the description provides adequate but incomplete context. It covers the 'what' and gives some usage guidance, but lacks important behavioral information about safety, permissions, and error handling that would be crucial for an AI agent to use this tool responsibly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the baseline is 3. The description doesn't add any parameter-specific information beyond what's already documented in the schema. It mentions 'sed patterns' which relates to the 'pattern' parameter, but this is already covered by the schema's example. No additional semantic context is provided for any parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('make small edits', 'pattern replacements', 'simple text transformations') and identifies the resource ('files'). It distinguishes from siblings like 'awk_process' and 'perl_edit' by specifying 'sed patterns', but doesn't explicitly differentiate from 'quick_replace' or 'line_edit' which might have overlapping functionality.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides implied usage guidance by mentioning 'efficient for single-line changes, pattern replacements, and simple text transformations', which suggests when this tool is appropriate. However, it doesn't explicitly state when NOT to use it or name specific alternatives among the sibling tools, leaving some ambiguity about tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/MikeyBeez/mcp-smalledit'

If you have feedback or need assistance with the MCP directory API, please join our Discord server