Please help me write an AppleScript for "BBEdit". Thank you

AppleScript searches for the string “668265846” in the current document “BBEdit”. If it exists, it returns the Line Number and content of the line where the string is located

A couple of questions…

  • Is the file always open in bbedit? Does it have to be? Finding a matching line number would also be straightforward using command-line tools.
  • Is there only one occurrence of the target string? If not, then what?
  • Are the lines in the text numbered already?

Not sure exactly what you’re after but this script will find multiple lines that match the specified string and return them as paragraphs prefaced by the line (or paragraph) number.

set matchStr to "668265846"
tell application "BBEdit"
	tell project window 1
		set con to contents
		set paraCon to paragraphs of con
		set pc to count of paraCon -- count of paragraphs/lines
		
		set matchList to {} -- list of matching lines and line number
		repeat with p from 1 to pc
			if item p of paraCon contains matchStr then
				-- line number <tab> line contents
				set end of matchList to (p & tab & contents of item p of paraCon) as text
			end if
		end repeat
		-- matchList
	end tell
end tell

set AppleScript's text item delimiters to linefeed
set matchPara to matchList as text
set findString to "668265846"

tell application "BBEdit"
   tell its document 1
      set findResult to (find findString)
      if not found of findResult then return "" --not found
      set foundLine to startLine of found object of findResult
      return foundLine
   end tell
end tell
return foundLine

I mentioned the command line earlier. Here is a solution using grep.

set cf to POSIX path of (((path to desktop) & "page.txt") as text)
set matchStr to "'668265846'"
do shell script "cat " & cf & " | grep -n " & matchStr

In case the text uses returns rather than linefeeds, they can be converted using tr.

do shell script "cat " & cf & " | tr \"\\r\" \"\\n\" | grep -n " & matchStr