read copy last line from text file - applescript

How to read the last line from a text file and copy part of this line to another text file?
To be more clear lets say that we have a text file (a.txt) containing the text below:
11:22:33 : first line text
11:22:35 : second line text
My need is to copy from the last line "11:22:35 : second line text" only the "second line text" and paste this string to another txt file (b.txt).
Before the paste b.txt file must first be cleared.

It's easiest do delegate this task to a shell command invoked with do shell script:
# Determine input and output file paths.
# Note: Use POSIX-format paths ('/' as the separator).
set inFile to "/path/to/a.txt"
set outFile to "/path/to/b.txt"
# Use a shell command to extract the last line from the input file using `sed`
# and write it to the output file.
do shell script "sed -n '$ s/.*: \\(.*\\)/\\1/p' " & quoted form of inFile & ¬
" > " & quoted form of outFile
Note: The embedded sed command looks like this, with the extra \ instances that are required by embedding it in an AppleScript string removed:
sed -n '$ s/.*: \(.*\)/\1/p'
Using the shell makes for a concise, but somewhat arcane solution.
Here's the AppleScript equivalent, which is easier to read, but also much more verbose:
This variant reads the input file line by line:
# Determine input and output file paths.
# Note: Use POSIX-format paths ('/' as the separator).
set inFile to "/path/to/a.txt"
set outFile to "/path/to/b.txt"
# Read the input file line by line in a loop.
set fileRef to open for access POSIX file inFile
try
repeat while true
set theLine to read fileRef before linefeed
end repeat
on error number -39 # EOF
# EOF, as expected - any other error will still cause a runtime error
end try
close access fileRef
# theLine now contains the last line; write it to the target file.
set fileRef to open for access POSIX file outFile with write permission
set eof of fileRef to 0 # truncate the file
write theLine & linefeed to fileRef # Write the line, appending an \n
close access fileRef
If reading the input file as a whole is acceptable, a much simpler solution is possible:
set inFile to "/path/to/a.txt"
set outFile to "/path/to/b.txt"
# Read the input file into a list of paragraphs (lines) and get the last item.
set theLastLine to last item of (read POSIX file inFile using delimiter linefeed)
# Write it to the target file.
do shell script "touch " & quoted form of outFile
write theLastLine to POSIX file outFile
Note the simplified way of writing to the target file, without needing to open and close the file explicitly.
Also, unlike when using write with a file reference, a trailing newline (\n) is added automatically when you target a file [object] directly.
However, this only works if the target file already exists, which is what the auxiliary do shell script command ensures (via standard utility touch).
If the file didn't exist yet, "casting" the file path to POSIX file would fail.

It's really handy to learn the ins and outs of "open for access". Here's your script:
set sourcePath to (path to desktop as string) & "a.txt"
set destinationPath to (path to desktop as string) & "c.txt"
-- set lastParagraph to last paragraph of (read file sourcePath) -- could error on unix text files
set lastParagraph to last item of (read file sourcePath using delimiter linefeed)
set fileReference to open for access file destinationPath with write permission
try
set eof of fileReference to 0 -- erases the file
write lastParagraph to fileReference
close access fileReference
on error
close access fileReference
end try

Related

How to batch rename files in a terminal?

I want to rename the files in a directory to sequential numbers.
stars_01_012.png
stars_01_014.png
stars_01_015.png
stars_01_017.png
stars_02_012.png
stars_02_014.png
stars_02_015.png
stars_02_017.png
And change it into
stars_01_001.png
stars_01_002.png
stars_01_003.png
stars_01_004.png
stars_02_001.png
stars_02_002.png
stars_02_003.png
stars_02_004.png
Relatives but not completely:
How to Batch Rename Files in a macOS Terminal?
How can I batch rename files using the Terminal?
You can do it with rename which you can install on macOS with homebrew using:
brew install rename
The command then looks like this:
rename --dry-run -X -e 'my #parts=split /_/; my $this=$parts[0].$parts[1]; if(!defined($ENV{previous}) || $this ne $ENV{previous}){$ENV{previous}=$this; $ENV{N}=0}; $ENV{N}=$ENV{N}+1; $_ = $parts[0]."_".$parts[1]."_".$ENV{N}' *png
Sample Output
'stars_01_012.png' would be renamed to 'stars_01_1.png'
'stars_01_014.png' would be renamed to 'stars_01_2.png'
'stars_01_015.png' would be renamed to 'stars_01_3.png'
'stars_01_017.png' would be renamed to 'stars_01_4.png'
'stars_02_012.png' would be renamed to 'stars_02_1.png'
'stars_02_014.png' would be renamed to 'stars_02_2.png'
'stars_02_015.png' would be renamed to 'stars_02_3.png'
'stars_02_017.png' would be renamed to 'stars_02_4.png'
'stars_88_099.png' would be renamed to 'stars_88_1.png'
Explanation:
my #parts=split /_/ splits the filename into 3 parts using the underscore as the separator,
my $this=$parts[0].$parts[1] saves the first two parts simply concatenated together, e.g. "stars01",
the if statement tests if either of the first two parts have changed, then
$ENV{previous}=$this; $ENV{N}=0 saves the current stem of the filename in an environment variable called previous and the current sequential counter in another environment variable N,
$ENV{N}=$ENV{N}+1 increments the sequential counter, and
$_ = $parts[0]."_".$parts[1]."_".$ENV{N} creates the new output filename from the various parts.
If that all looks correct, remove the --dry-run and run it again - probably in a spare directory with a copy of your files until you are sure all is ok :-)
The above may be easier to read like this:
#!/bin/bash
rename --dry-run -X -e '
my #parts=split /_/; # split filename into parts based on underscore
my $this=$parts[0].$parts[1]; # save first two parts of filename in $this
# see if it is a new stem
if(!defined($ENV{previous}) || $this ne $ENV{previous}){
$ENV{previous}=$this; $ENV{N}=0}; # save new initial part, reset N
$ENV{N}=$ENV{N}+1; # increment N
$_ = $parts[0]."_".$parts[1]."_".$ENV{N} # formulate new filename from parts
' *png
Change the last line to the following if you want to zero-pad the numbers out to three digits:
$_ = sprintf("%s_%s_%03d",$parts[0],$parts[1],$ENV{N}) # formulate new filename from parts
Note:
I save the previous file prefix and sequential counter into environment variables to preserve them between files - there may be easier ways - if anyone knows, please ping me! Thanks.
You can also create an applescript script, using the Terminal commandline.
below a script to copy in the script editor
set thefile to do shell script "ls The_path_of_your_files" that you wish to rename '"with in common the extension (in your example .png) which gives:
**set thefile to do shell script "ls The_path_of_your_files/*.png"
set AppleScript's text item delimiters to return
set chFile to text items of thefile
set AppleScript's text item delimiters to ""
set n to count chFile
repeat with i from 1 to n
set rnFile to item i of chFile
set nwname to (do shell script "echo" & quoted form of rnFile & "| sed 's # stars_01_01 # stars_01_00 #'")
set endFile to (do shell script "mv -f" & quoted form of rnFile & "" & quoted form of nwname)
end repeat**
which is equivalent to the rename multiple files function of the Finder
Just a rough answer, why use terminal script?
You can just use the Finder with its rename function
by selecting the common part of all your files in your example "stars_01_01" and replacing it with "stars_01_00", this will lead to the same result without having to write a script with :
sed 's#stars_01_01#stars_01_00#g'

Search and delete specific line of text in txt file - applescript

I would like to search the contents of a .txt file for a specific line of text and delete only that line from the .txt file.
I want to specify the line of text to find as a variable. For example:
set lineOfTextToDelete to "The quick brown fox jumps over the lazy dog."
Contents before:
Let's say the contents of my TestDelta.txt file is:
This is a a paragraph of text.
This is another line of text.
The quick brown fox jumps over the lazy dog.
Here is another line
Contents after:
The following shows the contents of the TestDelta.txt that I want after running the script. As you can see the string which has been assigned to the lineOfTextToDelete variable, i.e. "The quick brown fox jumps over the lazy dog." has been deleted from the contents of the file.
This is a a paragraph of text.
This is another line of text.
Here is another line
What I've tried so far:
Below is what I've tried, however I'm unsure what I should do next?
set txtfile to "Macintosh HD - Data:Users:crelle:Desktop:TestDelta.txt" as alias
set thisone to read txtfile
set theTextList to paragraphs of thisone
Can anyone help show me what to do?
Here are, in no particular order, a couple of solutions to consider.
Before usage I recommend creating a backup copy of any .txt file that you're going to try them with. These scripts can potentially cause loss of valuable data if not used carefully.
If you have any concerns regarding assignment of the correct filepath to either;
The txtFilePath variable in Solution A
The txtFilePath property in Solution B
then replace either of those lines with the following. This will enable you to choose the file instead.
set txtFilePath to (choose file)
Solution A: Shell out from AppleScript and utilize SED (Stream EDitor)
on removeMatchingLinesFromFile(findStr, filePath)
set findStr to do shell script "sed 's/[^^]/[&]/g; s/\\^/\\\\^/g' <<<" & quoted form of findStr
do shell script "sed -i '' '/^" & findStr & "$/d' " & quoted form of (POSIX path of filePath)
end removeMatchingLinesFromFile
set txtFilePath to "Macintosh HD - Data:Users:crelle:Desktop:TestDelta.txt"
set lineOfTextToDelete to "The quick brown fox jumps over the lazy dog."
removeMatchingLinesFromFile(lineOfTextToDelete, txtFilePath)
Explanation:
The arbitrarily named removeMatchingLinesFromFile subroutine / function contains the tasks necessary to meet your requirement. It lists two parameters; findStr and filePath. In its body we "shell out" twice to sh by utilizing AppleScript's do shell script command.
Let's understand what's happening here in more detail:
The first line that reads;
set findStr to do shell script "sed 's/[^^]/[&]/g; s/\\^/\\\\^/g' <<<" & quoted form of findStr
executes a sed command. The purpose of this command is to escape any potential Basic Regular Expression (BRE) metacharacters that may exist in the given line of text that we want to delete. Utlimately it ensures each character in the given string is treated as a literal when used in the subsequent sed command - thus negating any "special meaning" the metacharacter has.
Refer to this answer for further explanation. Essentially it does the following:
Every character except ^ is placed in its own character set [...] expression to treat it as a literal.
Note that ^ is the one char. you cannot represent as [^], because it has special meaning in that location (negation).
Then, ^ chars. are escaped as \^.
Note that you cannot just escape every char by putting a \ in front of it because that can turn a literal char into a metachar, e.g. \< and \b are word boundaries in some tools, \n is a newline, \{ is the start of a RE interval like \{1,3\}, etc.
Credit for this SED pattern goes to Ed Morton and mklement0.
So, given that the string assigned to the variable named lineOfTextToDelete is:
The quick brown fox jumps over the lazy dog.
we actually end up assigning the following string to the findStr variable after it has been parsed via the sed command:
[T][h][e][ ][q][u][i][c][k][ ][b][r][o][w][n][ ][f][o][x][ ][j][u][m][p][s][ ][o][v][e][r][ ][t][h][e][ ][l][a][z][y][ ][d][o][g][.]
As you can see each character is wrapped in opening and closing square brackets, i.e. [], to form a series of bracket expressions.
To further demonstrate what's happening; launch your Terminal application and run the following compound command:
sed 's/[^^]/[&]/g; s/\^/\\^/g' <<<"The quick brown fox jumps over the lazy dog."
Note When running the aforementioned compound command directly via the Terminal the sed pattern contains less backslashes (\) in comparison to the pattern specified in the AppleScript. This is because AppleScript strings require any backslash to be escaped with an additional backslash.
The second line reading;
do shell script "sed -i '' '/^" & findStr & "$/d' " & quoted form of (POSIX path of filePath)
executes another sed command via the shell. This performs the task of finding all instances of the given line of text in the file and deletes it/them.
The -i option specifies that the file is to be edited in-place, and requires a following empty string argument ('') when using the BSD version of sed that ships with macOS.
The '/^" & findStr & "$/d' part is the pattern that we provide to sed.
The ^ metacharacter matches the null string at beginning of the pattern space - it essentially means start matching the subsequent regexp pattern only if it exists at the beginning of the line.
The Applescript findStr variable is the result we obtained via the previous sed command. It is concatenated with the preceding pattern part using the & operator.
The $ metacharacter refers to the end of pattern space, i.e. the end of the line.
The d is the delete command.
The & quoted form of (POSIX path of filePath) part utilizes AppleScript's POSIX path property to transform your specified HFS path, i.e.
Macintosh HD - Data:Users:crelle:Desktop:TestDelta.txt
to the following POSIX-style path:
/Macintosh HD - Data/Users/crelle/Desktop/TestDelta.txt
The quoted form property ensures correct quoting of the POSIX-style path. For example, it ensures any space character(s) in the given pathname are interpreted correctly by the shell.
Again, to further demonstrate what's happening; launch your Terminal application and run the following compound command:
sed -i '' '/^[T][h][e][ ][q][u][i][c][k][ ][b][r][o][w][n][ ][f][o][x][ ][j][u][m][p][s][ ][o][v][e][r][ ][t][h][e][ ][l][a][z][y][ ][d][o][g][.]$/d' ~/Desktop/TestDelta.txt
Let's understand how to use the aforementioned removeMatchingLinesFromFile function:
Firstly we assign the same HFS path that you specified in your question to the arbitrarily named txtFilePath variable:
set txtFilePath to "Macintosh HD - Data:Users:crelle:Desktop:TestDelta.txt"
Next we assign the line of text that we want to find and delete to the arbitrarily named lineOfTextToDelete variable:
set lineOfTextToDelete to "The quick brown fox jumps over the lazy dog."
Finally we invoke the custom removeMatchingLinesFromFile function, passing in two required arguments namely; lineOfTextToDelete and txtFilePath:
removeMatchingLinesFromFile(lineOfTextToDelete, txtFilePath)
Solution B: Using vanilla AppleScript without SED:
This solution provided below does not utilize the shell, nor SED, and produces the same desired result as per Solution A.
property lineOfTextToDelete : "The quick brown fox jumps over the lazy dog."
property txtFilePath : alias "Macintosh HD - Data:Users:crelle:Desktop:TestDelta.txt"
removeMatchingLinesFromFile(lineOfTextToDelete, txtFilePath)
on removeMatchingLinesFromFile(findStr, filePath)
set paraList to {}
repeat with aLine in getLinesFromFile(filePath)
if contents of aLine is not findStr then set paraList to paraList & aLine
end repeat
set newContent to transformListToText(paraList, "\n")
replaceFileContents(newContent, filePath)
end removeMatchingLinesFromFile
on getLinesFromFile(filePath)
if (get eof of filePath) is 0 then return {}
try
set paraList to paragraphs of (read filePath)
on error errorMssg number errorNumber
error errorMssg & errorNumber & ": " & POSIX path of filePath
end try
return paraList
end getLinesFromFile
on transformListToText(ListOfStrings, delimiter)
set {tids, text item delimiters} to {text item delimiters, delimiter}
set content to ListOfStrings as string
set text item delimiters to tids
return content
end transformListToText
on replaceFileContents(content, filePath)
try
set readableFile to open for access filePath with write permission
set eof of readableFile to 0
write content to readableFile starting at eof
close access readableFile
return true
on error errorMssg number errorNumber
try
close access filePath
end try
error errorMssg & errorNumber & ": " & POSIX path of filePath
end try
end replaceFileContents
Explanation:
I'll keep this explanation brief as the code itself is probably easier to comprehend than Solution A.
The removeMatchingLinesFromFile subroutine essentially performs the following with the aid of additional helper functions:
read's the contents of the given .txt file via the getLinesFromFile function and return's a list. Each item in the returned list holds each line/paragraph of text found in the .txt file content.
We then loop through each item (i.e. each line of text) via a repeat statement. If the contents of each item does not equal the given line of text to find we store it in another list, i.e. the list assigned to the paraList variable.
Next, the list assigned to the paraList variable is passed to the transformListToText function along with a newline (\n) delimiter. The transformListToText function returns a new string.
Finally, via the replaceFileContents function, we open for access the original .txt file and overwrite its contents with the newly constructed content.
Important note applicable to either solution: When specifying the line of text that you want to delete, (i.e. the string that is assigned to the lineOfTextToDelete variable), ensure each and every backslash \ that you may want to search for is escaped with another one. For example; if the line that you want to search for contains a single backslash \ then escape it to become two \\. Similarly if the line that you want to search for contains two consecutive backslashes \\ then escape each one to become four \\\\, and so on.

GNUPLOT : A better way of piping data into gnuplot script

I have a gnuplot script like this (simplified)
reset session
set terminal pngcairo enhanced font "Times,25" size 800,400
filename = ifilename
stats filename nooutput
N = STATS_columns
M = STATS_records
set angles degrees
set size square 1.25,1
set output ofilename
# does some stuff
...
...
...
set parametric
plot \
for [i=2:N] filename u (posX($0, column(i))):(posY($0, column(i))) w p ps 1.2 pt 7 lc rgb lcolor(i-2)
What I want to do is define ifilename (input file) and ofilename (output file) via a shell script.
So I thought the -e command might just be the one for the job.
So for the gnuploat part of the script I wroth this
gnuplot -e "ifilename='data/points_data1.dat'; ofilename='plot1'" chart.gp
but it threw the error
"chart.gp" line 8: undefined variable: ifilename
which refers to this line
filename = ifilename
I thought maybe that's because it's having some trouble parsing two = signs so I removed that line and rewrote my shell script like this
gnuplot -e "filename='data/points_data1.dat'; ofilename='plot1'" chart.gp
but this time it threw the following error
"chart.gp" line 8: undefined variable: filename
What actually worked was this
echo "data/points_data$i.dat" | gnuplot chart.gp
where I replaced the line filename = ifilename with
FILE = system("read filename; echo $filename")
and every instance of filename with FILE in .gp script.
But I'm not sure how to use that syntax to also define the output file.
So I was wondering, is there a better way of piping shell input into gnuplot script?
Your original command almost worked. The invocation
gnuplot -e "ifilename='data/points_data1.dat'; ofilename='plot1'" chart.gp
correctly defined the input and output file names. But then you clobbered them inside the chart.gp script by issuing the command
reset session
which clears all variable definitions including the ones you specifically wanted. Remove that line from the script and you should be fine. If the intent of the "reset session" command was to make sure that no system-wide or private initialization file is used, then replace it with a "-d" on the command line:
gnuplot -d -e "ifilename='data/points_data1.dat'; ofilename='plot1'" chart.gp
FILE = system("read filename; echo $filename")
is actually fine.
If you want to pipe the output to some file you can just omit set output "something.png"
and instead you could just send the .png output directly to stdout by running a script like this
#!/usr/bin/env gnuplot
reset session
set terminal pngcairo enhanced font "Times,25" size 800,400
...
then you can pipe that output to a .png file like this
./chart.gp > mypng.png
So the final command would look something like this
echo "data/points_data$i.dat" | gnuplot chart.gp > plot$i.png

need to return "\" not "\\" in applescript to build bash command

Thanks for the help.
I'm trying to build a series of bash commands using Applescript. My problem is applescript using \ as an escape character. so when it returns my strings its returning \\ not \ as needed. Has anyone found a way to return a string with a single \?
Also, previous help I've received on this people will say "if you display dialog it will say \ not \\" which is correct however I'm not attempting to display text I need to pass these strings on to bash.
--get all the finder info
tell application "Finder"
set selCnt to selection as list
if (count of items in selCnt) is equal to 1 then
set theDir to the selection as alias
set theDir to POSIX path of theDir
else if ((count of items in selCnt) is greater than 1) then
display dialog "Please select only one directory. ie: 'Documents'"
else if (count of items in selCnt) is equal to 0 then
set theDir to target of window 1 as alias
set theDir to POSIX path of theDir
else
display dialog "What do you think you're doing?"
end if
end tell
--rename strings with spaces
set t to theDir
set t to tid(t, " ") -- converts to a list of text items
set t to tid(t, "\\ ") -- converts back to tex a list odf text items
on tid(input, delim)
set {oldTID, my text item delimiters} to {my text item delimiters, delim}
if class of input is list then
set outputA to input as text
else
set outputA to text items of input
end if
set my text item delimiters to oldTID
return outputA
end tid
set theDir to result
--strings setup
set cdStr to "cd " & theDir
set stringA to ".doc"
set stringB to "\\"
set delDoc to "find . -name " & quoted form of stringA & " -exec rm {} " & stringB & ":"
set stringA to ".exl"
set stringB to "\\"
set delExl to "find . -name " & quoted form of stringA & " -exec rm {} " & stringB & ":"
--execute shell scripts
set theCmd to cdStr & return & delDoc & return & delExl
return theCmd
(*
do shell script cdStr
do shell script delExl
do shell script delDoc
*)
You simply need to escape a backslash with a backslash to pass on that string.
set foo to "\\"
will set foo to a single "\". You can verify this using any of the following:
display dialog foo
log foo
return foo
do shell script "echo \\$foo"
Run this last command, and it returns "$foo", proving that the shell command correctly received a single slash, which in this instance tells the shell command to ignore the special significance of $. If it had sent two slashes to the shell command, you would've gotten an error, or possibly a literal slash.
You can psych yourself out by getting confused by your editor's display of "\", but the results end up working.
You don't state in your question what is making you think it's not behaving correctly. What does "it freaks out" mean?
I was able to figure everything out using bash commands mostly. Then I was able to create a service which ran when i hit a certain key set like "cmd + option + R." All the user has to do is select the folder and hit the keys and the program will erase all of the files with the specific extension. step 2 from my notes below allow bash to recognize the source which is determined by the first open window of Finder.
Again sorry for all the formatting trouble this is only my second ever post in stackoverflow
first modify the .bash_profile. Open it via terminal
open ~/.bash_profile -a TextEdit
copy and past script into the txt file then save. This allows you to now issue a command “cdf”
cdf () {
theFinderPath=osascript <<END
tell application "Finder"
try
set thePath to get the POSIX path of (folder of the front window as string)
on error
set thePath to get the POSIX path of (path to desktop folder as string)
end try
end tell
END
cd "$theFinderPath";
}
rewrite script to include new command and then save this to the root of your “Documents” folder.
3.
! /bin/bash
cd to the path of the front Finder window
cdf
find . -name ‘.doc’ -exec rm {} \; #deletes all doc files
find . -name ‘.exe’ -exec rm {} \; #deletes all exe files
Now using Automator you can write a simple code that will issue this command from a keystroke.
bash -x /Users/username/Documents/sh/script.sh || true

How to select line in AppleScript

I'm trying to figure out how to use Text Item Delimiters on a long line of text that is in a log file.
Within the log of information there is always a constant phrase that i'm searching for which leads me to the line of text. I'm getting to the line I want by searching for "[Constant]", for example.
The problem I'm having is that I can't select the whole line to perform a Delimiter. Below is a very basic example of what the log looks like.
qwertyuiop
mnbvcxza
oqeryuiiop
[Constant] 1234567890123456-098765432109876-8765432118976543
odgnsgnsanfadf
joiergjdfmgadfs
Any advice would be appreciated.
So far I'm using:
repeat 16 times
key code 124 using (shift down)
end repeat
Which does the job fine but it is clunky.
An easy way to find a line of text containing a specific string is the shell command grep.
set theConstant to "Constant"
set theText to "qwertyuiop
mnbvcxza
oqeryuiiop
Constant 1234567890123456-098765432109876-8765432118976543
odgnsgnsanfadf
joiergjdfmgadfs"
set foundLine to do shell script "echo " & quoted form of theText & " | tr '\\r' '\\n' | grep " & quoted form of theConstant
the tr part to replace return (0x0d) characters with linefeed (0x0a) characters is necessary to conform to the shell line separator requirements.
If the constant contains special characters it's a bit more complicated, because you have to escape the characters before passing them to the shell.
set theConstant to "\\[Constant\\]"
set theText to "qwertyuiop
mnbvcxza
oqeryuiiop
[Constant] 1234567890123456-098765432109876-8765432118976543
odgnsgnsanfadf
joiergjdfmgadfs"
set foundLine to do shell script "echo " & quoted form of theText & " | tr '\\r' '\\n' | grep " & quoted form of theConstant
If you want to read the text from a file on disk you can use this
set logFile to (path to library folder from user domain as text) & "Logs:myLogFile.log"
set theText to read file logFile as «class utf8»
Your question is puzzling. Do you want to parse a text/log file or a script to work with the GUI of some app? Because that is what your code suggests...
If you want to parse a log file, which is easier, you can use the good old Unix tools OSX comes with. You can use them from inside Applescript like this...
set logfile to "/some/path/file.log"
# Quote the string in case it contains spaces... or add single quotes above...
set qlogfile to quoted form of logfile
# Prepare the shell command to run
set cmd to "grep '^\\[Constant]' " & qlogfile & " | cut -c 12- | tr '-' '\\n'"
# Run it and capture the output
try
set cmdoutput to (do shell script cmd)
on error
# Oh no, command errored. Best we do something there
end try
The result looks like this...
tell current application
do shell script "grep '^\\[Constant]' '/some/path/file.log' | cut -c 12- | tr '-' '\\n'"
--> "1234567890123456
098765432109876
8765432118976543"
end tell
Result:
"1234567890123456
098765432109876
8765432118976543"
So to break it down the shell commands are,
grep ... | will read the contents of the file and select all lines that start ^ with the text [Constant] and pass what it finds | on to the next command
cut cuts out the characters from position 12 until the end - of the line
tr replaced any character - with \n which is the code for newline in unix.
The \\ you see are due to having it executed from inside Applescript. You only need on if you run it inside Terminal.
If you care to know the contents of one line from the other, then remove the last command | tr '-' '\\n' and it will return
Result:
"1234567890123456-098765432109876-8765432118976543"

Resources