Jump to content

Adding line numbers to selected text


Recommended Posts

I'm looking for a workflow to take the selected text and add numbers. A post from this forum in 2013 had a broken link to the completed workflow.

e.g. input:

Yes

No

Output:

1. Yes

2. No

 

I'm a noob when it comes to writing workflows and bash, but this script works on the command line but I keep getting "ERROR: Add Numbers to Text Selection[Run Script] Debug: Received input: ''
No input provided." in Alfred.

 

I've checked my accessibility settings. Hotkey is set to Pass through to Workflow with argument Selection in macOS, language bin/bash, with input as argv.

 

#!/bin/bash

# Read input from stdin
input=""
while IFS= read -r line; do
    input+="$line\n"
done

# Remove the last newline added in the loop
input=${input%\\n}

# Debugging: Echo input to see what is being passed
echo "Debug: Received input: '$input'" >&2

# Check if input is empty
if [[ -z "$input" ]]; then
    echo "No input provided." >&2
    exit 1
fi

# Number each line and format it
line_number=1
echo -e "$input" | while IFS= read -r line; do
    echo "${line_number}. $line"
    ((line_number++))
done

 

Link to comment

Welcome @sweetgrass,

 

When sending text to a script you’re not doing it as continuous input but rather as an argument. In other words, you have to use $1. See Alfred’s placeholder text when creating a new Run Script with /bin/bash set as the language.


But even so, the code can be greatly simplified. There is a command-line tool in macOS whose whole purpose is counting lines. You should be able to replace the whole code with a single line:

 

/usr/bin/nl -ba -d. -s'. ' -w 1 <<< "${1}"

 

Run man nl in a terminal for an explanation of the options.

 

That should return the same format you’re looking for. Though personally I don’t like that numbers can push lines to the right, so I’d do something like:

 

readonly digits="$(wc -l <<< "${1}" | tr -d '\n ' | wc -c | tr -d '\n ')"
/usr/bin/nl -b a -d . -s '. ' -w "${digits}" <<< "${1}"

 

Link to comment
  • 2 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...