yusf
yusf

Reputation: 123

Shell script to set screen resolution values in a file

I want a shell script that

  1. grabs my current screen resolution, (solved)
  2. searches a file for the line containing the resolution setting,
  3. replaces the old resolution setting in the file with the current one

So far (thanks!) I've got the command for getting the current screen resolution data:

system_profiler SPDisplaysDataType | awk '/Resolution/ {
    print "screenwidth \""$2"\"";
    print "screenheight \""$4"\"";
}'

The lines that should be written to respectively begins with:

screenwidth "VALUE1"
screenheight "VALUE2"

How do I write the results to the file on the "VALUE" positions?

(I'm quite a beginner in the world of shell scripts)

Upvotes: 2

Views: 651

Answers (2)

Kent
Kent

Reputation: 195269

If I understood you right,

sys..|grep..|awk ..$2   is new widht
sys..|grep..|awk ..$4   is new height

you want to replace value1/2 in old file with new values from above lines

-- old file  --
screenwidth "VALUE1"
screenheight "VALUE2"

then you could do in one shot:

sys..|grep..|awk 'NR==FNR{w=$2;h=$4;next}/screenwidth/{$0="screenwidth \""w"\"";} /screenheight/{$0="screenheight \""h"\""}1' -  oldfile

see this test example:

#I simulate your sys..|grep.. with echo

kent$  cat old.txt
foo
screenwidth "VALUE1"
screenheight "VALUE2"
bar

kent$  echo "foo 200 bar 400"|awk 'NR==FNR{w=$2;h=$4;next}/screenwidth/{$0="screenwidth \""w"\"";} /screenheight/{$0="screenheight \""h"\""}1' -  old.txt    
foo
screenwidth "200"
screenheight "400"
bar

Upvotes: 2

chepner
chepner

Reputation: 532418

One call to awk is sufficient (and grep is unnecessary):

system_profiler SPDisplaysDataType | awk '/Resolution/ {
    print "screenwidth \""$2"\"";
    print "screenheight \""$4"\"";
}'

Upvotes: 2

Related Questions