You can make a difference in the Apple Support Community!

When you sign up with your Apple Account, you can provide valuable feedback to other community members by upvoting helpful replies and User Tips.

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

How to get result (not return code) from grep into a variable

Hi,




Hopefully you can help me.




I have a text file containing a record for each photo - the line contains md5 tag whitespace and the full path/filename for each photo. I select a folder that I believe contains a lot of dupes and then take the md5 tag for the first item in this and search the entire file so I will get at least one hit (the photo that I am searching with). If I find more than one I want to delete the full path/filename.




I am using grep to count the matches ===>> grep -c   "c9b09af7a76c7abe17ce9f15b6da3820" /Users/teba/tasks/photo_work/photo_md5_dir_list.csv |sed -r "s/\s+//g" | awk -F ":"  '{print $1,$2}' | sort -nr -k2| head -1




In terminal window it returns a number (in my case 3) however I can't get the result of grep into a variable to test it for greater than 1. (Only to a file)




I was going to write the script with AppleScript - if there is a better way please point it out to me




All of my scripting is done by grabbing ideas/solutions that all of you in the community have published - so thank you to everyone!




Any help would be appreciated.




Terry

Posted on Sep 26, 2024 4:12 PM

Reply
Question marked as Top-ranking reply

Posted on Sep 27, 2024 8:11 AM

There is another way to use do shell script in AppleScript:


use framework "Foundation"
use scripting additions

property NSArray : a reference to current application's NSArray

set theRangeStr to text returned of (display dialog "enter your page numbers: " default answer "") as text
set pageLst to paragraphs of my handle_pages(theRangeStr)
set outStr to ((NSArray's arrayWithArray:pageLst)'s componentsJoinedByString:return) as text
display dialog "Original: " & theRangeStr & return & return & outStr with title "Expanded Page Series"
return

on handle_pages(astr)
	return (do shell script "/bin/zsh -s <<'EOF' - " & astr's quoted form & "
#!/bin/zsh

typeset -ga values=() series=()
# strip any spaces from input string and remap any non-comma separator character ranges
str=\"${1:gs/ //}\"
strx=\"$(tr '[\\041-\\053\\056-\\057\\072-\\100\\137]' ',' <<<\"${str}\")\"

function range_expand () {
    local str=\"${1}\"
    values+=( ${(s:,:)str} )
    for n in $values;
    do
        [[ $n =~ '-' ]] || { series+=( $n ); continue}
        # expand series to sequence
        series+=( {${n:s/-/../}} )
    done
    return
}

range_expand \"${strx}\"
for n in $series; do print $n;done
unset values series
EOF")
end handle_pages

You can run this from the Script Editor, or directly from the command-line:

/usr/bin/osascript zsh_exp_range.applescript

In this example, you are running a full Zsh script from the do shell script and it can internally assign variables and return them via the print command.


Input dialog:



Result:


11 replies
Question marked as Top-ranking reply

Sep 27, 2024 8:11 AM in response to hgtefla

There is another way to use do shell script in AppleScript:


use framework "Foundation"
use scripting additions

property NSArray : a reference to current application's NSArray

set theRangeStr to text returned of (display dialog "enter your page numbers: " default answer "") as text
set pageLst to paragraphs of my handle_pages(theRangeStr)
set outStr to ((NSArray's arrayWithArray:pageLst)'s componentsJoinedByString:return) as text
display dialog "Original: " & theRangeStr & return & return & outStr with title "Expanded Page Series"
return

on handle_pages(astr)
	return (do shell script "/bin/zsh -s <<'EOF' - " & astr's quoted form & "
#!/bin/zsh

typeset -ga values=() series=()
# strip any spaces from input string and remap any non-comma separator character ranges
str=\"${1:gs/ //}\"
strx=\"$(tr '[\\041-\\053\\056-\\057\\072-\\100\\137]' ',' <<<\"${str}\")\"

function range_expand () {
    local str=\"${1}\"
    values+=( ${(s:,:)str} )
    for n in $values;
    do
        [[ $n =~ '-' ]] || { series+=( $n ); continue}
        # expand series to sequence
        series+=( {${n:s/-/../}} )
    done
    return
}

range_expand \"${strx}\"
for n in $series; do print $n;done
unset values series
EOF")
end handle_pages

You can run this from the Script Editor, or directly from the command-line:

/usr/bin/osascript zsh_exp_range.applescript

In this example, you are running a full Zsh script from the do shell script and it can internally assign variables and return them via the print command.


Input dialog:



Result:


Sep 27, 2024 7:54 AM in response to hgtefla

AppleScript will not return nbr_Found from your do shell script. Remove it and the $( ... ) syntax. Any double-quote inside the starting and ending double-quote of the do shell script must be escaped (e.g. "\"") and so must any other left-leaning backslash (e.g. \\s+)


set nbr_Found to (do shell script "grep -c \"c9b09af7a76c7abe17ce9f15b6da3820\" ~/tasks/photo_work/photo_md5_dir_list.csv | sed -r \"s/\\s+//g\" | awk -F \":\"  '{print $1,$2}' | sort -nr -k2 | head -1")


And now you know how painful it is to perform complicated things in a do shell script with fluent double-quotes and backslashes… 🤯

Sep 27, 2024 5:03 AM in response to hgtefla

Hi Bob Harris,


Could you help once more? -

--     Extract what photos (md5 record) you are trying to delete as dupes and put them in 


--     file photos_for_possible_deletion.txt






# Determine the input file's path.


set f to (choose file) # most probably the one above




# Read lines from file.


set lns to paragraphs of (read file f as «class utf8»)


-- display dialog "the line reads: " & lns




# Loop over lines read and copy each to the clipboard.


repeat with ln in lns


set the clipboard to ln


set myCommand to do shell script "nbr_Found=$(grep -c   "c9b09af7a76c7abe17ce9f15b6da3820" /Users/teba/tasks/photo_work/photo_md5_dir_list.csv |sed -r "s/\s+//g" | awk -F ":"  '{print $1,$2}' | sort -nr -k2| head -1)"




-- display dialog (the clipboard)


end repeat

I have tried to escape the quotes but I keep getting caught on something else. Currently (with the unchanged grep command) I get syntax error Expected end of line but found identifier (on the md5 string).


Thanks,


Terry

How to get result (not return code) from grep into a variable

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.