To insert text at a specific line in an existing Mac text file, use a Shortcuts shell action to create an edited copy, inspect it, then rename it in Finder. This walkthrough inserts one line before line 3 using a disposable example.

The task here is adding a line to a small, local plain-text file while keeping the surrounding lines in order. You’ll build a Finder shortcut that accepts exactly one file. The insertion text and line number live in the script, making the same edit easy to repeat on disposable copies.

What does “insert at line 3” mean?

In this article, insertion means placing new text before the existing numbered line. With three original lines, inserting Birch before line 3 produces four lines:

Position Original file Edited file
1 Cedar Cedar
2 Maple Maple
3 Willow Birch
4 — Willow

A line is a newline-delimited record, rather than a row created by visual wrapping in an editor. Blank lines count. The example uses ordinary UTF-8 plain text with LF line endings and a newline after its final line. Keep those conditions for this exercise; rich-text documents and files using other encodings or line endings need a different handling plan.

The command doing the edit is macOS sed. Its numeric addresses count lines starting at 1, and its i command writes insertion text before the addressed line. It normally writes the transformed content to standard output. Those documented behaviors let the shortcut build a separate result file. Apple’s distributed sed manual

Create a disposable text file

Open Terminal and paste this complete setup block. It creates a folder named Line Insert Demo on your Desktop and a three-line file named notes.txt. If that folder name already exists, setup stops; choose a fresh folder name before trying again.

/bin/sh <<'SH'
set -e
demo_dir="$HOME/Desktop/Line Insert Demo"
/bin/mkdir "$demo_dir"
printf '%s\n' 'Cedar' 'Maple' 'Willow' > "$demo_dir/notes.txt"
printf 'Created: %s\n' "$demo_dir/notes.txt"
SH

The folder creation deliberately omits the option that permits an existing directory. The file-writing step runs only after a new folder has been created, so this setup does not overwrite an earlier example. Apple’s shell documentation explains using printf and output redirection to create text files. Shell Input and Output

Keep this exercise inside that disposable folder. In Finder, open your Desktop and locate Line Insert Demo; you’ll select its notes.txt file after building the shortcut.

Build a Finder shortcut with the right input type

Create a shortcut named Insert Birch Before Line 3 in Shortcuts. Apple documents creating a shortcut with the toolbar’s Add button, naming it, and adding actions from the sidebar. Create a custom shortcut on Mac

Configure it as follows:

  1. Open the shortcut’s Details and enable Use as Quick Action, with Finder selected.
  2. In the shortcut’s input header, change the accepted content to Files, turning off the other types.
  3. Add the Run Shell Script action.
  4. Set its Shell to /bin/sh, its Input to Shortcut Input, and Pass Input to as arguments.
  5. Replace the action’s sample script with the complete program in the next section.

Apple documents enabling Finder shortcuts and limiting their accepted input types. Its Files type includes many kinds of documents, so this setting makes files available to the shortcut; it does not validate their text format. The script adds narrower checks. Run a shortcut while working on your Mac, Limit the input for a shortcut, Understanding input types

The input chain matters: Finder supplies a file to Shortcuts, and the shell action passes its path as an argument, available in the script as $1. Do not put a text-reading action before the shell action: this program needs the file’s path so it can read the existing file and choose a neighboring output name.

Apple confirms that Shortcuts for Mac supports running shell scripts directly in the editor. If scripting is disabled, choose Shortcuts > Settings, open Advanced, and enable Allow Running Scripts. Meet Shortcuts for macOS, Advanced Shortcuts settings

Insert the line and create a separate result

Paste this entire program into Run Shell Script. It requires one existing regular file, inserts Birch before line 3, and writes a neighboring file named by adding .inserted.txt to the source path.

#!/bin/sh
set -eu

fail() {
    printf '%s\n' "$1" >&2
    exit 1
}

[ "$#" -eq 1 ] || fail 'Select exactly one example text file.'
file=$1
line=3

case "$file" in
    /*) ;;
    *) fail 'The input must be an absolute file path.' ;;
esac

[ -f "$file" ] || fail 'The input file does not exist or is not a regular file.'
[ ! -L "$file" ] || fail 'Select the example file itself, not a symbolic link.'
[ -r "$file" ] || fail 'The input file cannot be read.'

count=$(/usr/bin/sed -n '$=' "$file") || fail 'Could not count the input lines.'
[ -n "$count" ] || fail 'The input file is empty.'
[ "$line" -le "$count" ] || fail 'The insertion line is beyond the end of the file.'

output="${file}.inserted.txt"
if [ -e "$output" ] || [ -L "$output" ]; then
    fail 'The output name already exists. Inspect or rename that result first.'
fi

if (
    set -C
    /usr/bin/sed "${line}i\\
Birch
" "$file" > "$output"
); then
    printf 'Created edited copy: %s\n' "$output"
else
    fail 'Could not finish the edited copy. Inspect any partial output before retrying.'
fi

The physical line breaks inside the sed expression are intentional. Keep the backslash after i, the following newline, and the inserted text on its own line. The command structure follows Apple’s distributed manual; it avoids relying on a compact insertion spelling copied from a different sed implementation. sed manual: commands and insertion text

The surrounding checks are the workflow’s decision rules. An insertion before a numbered line requires that line to exist. This program therefore rejects an empty file and a target beyond its last line. It also refuses an existing output name, while shell noclobber mode provides another check when opening the output.

The script reads the original and writes a separate file. If writing fails, the original remains available, but an incomplete output may remain. Treat an error as an unfinished operation and inspect that output before removing it or retrying. Run only one instance at a time and leave the source unchanged during the operation.

The action’s output is a text status message containing a path, not a Shortcuts file object. The edited file is created by the script’s redirection. Adding Save File afterward would save the action’s output rather than perform the intended line insertion. Apple documents Save File as a file-management sharing action; its documentation does not describe it as a numbered-line editor. About share actions in Shortcuts on Mac

Run it, inspect the result, and keep the original filename

In Finder, Control-click the disposable notes.txt file and choose Quick Actions, then Insert Birch Before Line 3. Apple documents this launch route. If the shortcut is missing, check that Finder is enabled in its details and that its accepted input includes Files. Run a shortcut while working on your Mac

After a successful run, the demo folder contains both notes.txt and notes.txt.inserted.txt. Open the latter and check that its contents are exactly:

Cedar
Maple
Birch
Willow

You can also inspect the output from Terminal with this complete command:

/bin/cat "$HOME/Desktop/Line Insert Demo/notes.txt.inserted.txt"

To put the edited content at the original pathname, close the example documents and perform these two renames in Finder. First confirm that notes.original.txt is unused; if it exists, choose another unused backup name.

  1. Select notes.txt, press Return, rename it to notes.original.txt, and press Return again.
  2. Select notes.txt.inserted.txt, press Return, rename it to notes.txt, and press Return again.
  3. Open the newly named notes.txt and verify the four lines.

Apple documents selecting an item and pressing Return to rename it. Preserve the final .txt extension in both names. If Finder reports a name collision, stop and inspect the existing item before choosing an unused name. Rename files, folders, and disks on Mac

This finishes with the edited content under notes.txt and the original content under notes.original.txt. It replaces which file occupies the original pathname; it does not preserve the original file’s identity or promise to carry over Finder tags, extended attributes, or other metadata.

Adjust the insertion without changing its meaning

For another disposable file, change line=3 to an existing line number and replace Birch with a simple single line of text. Keep the displayed insertion syntax intact. The example text intentionally contains no quotation marks, dollar signs, backticks, or backslashes; arbitrary text needs additional shell and sed quoting.

Use this decision table before editing the script:

Intended change What to do
Put text before the first line Set line=1 on a nonempty example file.
Put text before another existing line Set line to that positive line number.
Add text after the last line Use a separate append operation; this program rejects a nonexistent target line.
Insert into an empty file Create its initial content separately; there is no existing line to address.
Run the same shortcut twice Inspect the earlier output first. After replacing the original, another run inserts another copy of the text.

For this desktop task, the useful checkpoints are the selected file, the insertion position, the completed result, and the final filename. Once the four-line example is correct, the same sequence gives you a clear way to test another simple insertion while keeping the starting text available.

Sources