Issue
I need help with a bash script modification for one script that I got a few days ago. It removes a text. This question is asking to replace a text.
The script will read the values of file "Install.txt", (sample content):
TRUE 203
TRUE 301
TRUE 602
TRUE 603
The numbers corresponds with the same number in file: "ExtInstaller.sh", (sample content):
false Styles "Diary Thumbnails" #202
false Styles "My Border Style" #203
false Menus "My Menu" #301
false Decorations "Diary Decor" #501
false Modules "Control Pager Button" #601
false Modules "Dash To Dock" #602
false Modules "Desk Switch" #603
All lines are "false". The script will change the text "false" to "TRUE" of the corresponding line that has the same number as in file "Install.txt". For example, TRUE 203 changes the line with #203.
false Styles "My Border Style" #203
to
TRUE Styles "My Border Style" #203
The previous script that I got a few days ago on this forum removes the text in the 1st column. This question is to replace the 1st column (false) with the text "TRUE".
The 1st code string is the same.
search=$(awk 'BEGIN{OFS=ORS=""}{if(NR>1){print "|"}print $2;}' Install.txt)
The 2nd code string I have tried different modifications:
sed -i -r "s/^false/TRUE (.*#($search))$/\1/g" ExtInstaller.sh
and
sed -r "s/^false (.*($search))$/\TRUE/g" ExtInstaller.sh
The 1st one gives errors and the 2nd replaces "false" with "TRUE" but doesn't show the corresponding text string.
false Styles "Diary Thumbnails" #202
TRUE
TRUE
false Decorations "Diary Decor" #501
false Modules "Control Pager Button" #601
TRUE
TRUE
Any help is appreciated. Thank you.
Solution
Would you please try the following:
awk '
NR==FNR {a["#"$2] = $1; next} # array maps #num to "TRUE"
$NF in a {$1 = a[$NF]} # if #num is in the array, replace
1' Install.txt ExtInstaller.sh
Output:
false Styles "Diary Thumbnails" #202
TRUE Styles "My Border Style" #203
TRUE Menus "My Menu" #301
false Decorations "Diary Decor" #501
false Modules "Control Pager Button" #601
TRUE Modules "Dash To Dock" #602
TRUE Modules "Desk Switch" #603
- The statement
NR==FNR {command; next}
is an idiom to execute the command with the file in the 1st argument (Install.txt) only. a["#"$2] = $1
is an array assignment which maps e.g key#203
to valueTRUE
.- The condition
$NF in a
meets if the last field value$NF
in the line of the fileExtInstaller.sh
is defined as a key of arraya
. $1 = a[$NF}
replaces the 1st fieldfalse
with the value of the arrayTRUE
.- The final
1
tellsawk
to print current line.
Answered By - tshiono Answer Checked By - Willingham (WPSolving Volunteer)