0

I'm trying to extract specific lines from the output of a command that outputs a lot of lines of text. I've hit a bit of a wall at this point:

pathsText=$(system_profiler SPApplicationsDataType | egrep '^\s+Location:\s+.*$')

This extracts the correct lines, but it puts them all into a single long line, with matches separated by spaces rather than newlines.

In other words, I'm expecting something like this:

  Location: /a/b
  Location: /c/d/e
  ...

And that's what I get if I run that same egrep command against a text file containing the output of system_profiler SPApplicationsDataType in the Terminal. But the command above does not put that into pathsText. Instead, it's giving me:

Location: /a/b Location: /c/d/e ...

Unfortunately, I can't just split based on spaces, because the paths contained in each line may contain spaces.

What am I doing wrong?

T. Reed
  • 181
  • 1
  • 9
  • It is unclear how you checked "Instead, it's giving me.....". After reading this question I was unable to reproduce something that seems to be a problem..... – Luuk Sep 17 '21 at 18:23
  • @Luuk Using echo to display $pathsText results in something with no line breaks. I know this isn't a problem with echo, however, because if I echo the results of system_profiler SPApplicationsDataType directly, the line breaks are present. Piping to egrep seems to cause them to be lost. – T. Reed Sep 17 '21 at 19:36

1 Answers1

1

Still not reproducable:

luuk@mini ~ % pathsText=$(system_profiler SPApplicationsDataType | egrep '^\s+Location:\s+.*$')
luuk@mini ~ % echo $pathsText 
      Location: /System/Applications/System Preferences.app
      Location: /System/Applications/Utilities/Terminal.app
      Location: /System/Applications/TV.app
      Location: /System/Applications/FaceTime.app
      Location: /System/Applications/TextEdit.app
      Location: /System/Applications/Time Machine.app
      Location: /System/Applications/App Store.app
      Location: /System/Library/ColorSync/Calibrators/Display Calibrator.app
      Location: /System/Library/CoreServices/P.....

EDIT:

The answer is here:

https://www.google.com/search?q=macos+assign+variable+looses+carriage+return+of+line+feed

finding a link on stackoverflow.com to:

How to preserve line breaks when storing command output to a variable?

Luuk
  • 12,245
  • 5
  • 22
  • 33
  • Please try putting this in a shell script and running it, rather than doing it directly from the command line. Within a shell script, it gives me different results. – T. Reed Sep 17 '21 at 20:00
  • The edit solved it, thanks! – T. Reed Sep 17 '21 at 20:13