Unix & Sed noob here!
I have a requirement where I need to put a suffix ",waive" in case a line in a report containing a matching string.The matching string is part of another file "waive.txt". I am also trying to perform these operations on a copy of the main report.
Here is how the report looks like:
i love apple_tart as a desert
banana is full of potassium and iron
there are so many helath benefits of apple eating
the king of fruit is mango
there are apple_pie of many variety
Here is how waive.txt looks like:
apple_pie
banana
This is my expeted output which I want in the same file :
i love apple_tart as a desert
banana is full of potassium and iron,waive
there are so many helath benefits of apple eating
the king of fruit is mango
there are apple_pie of many variety,waive
This is the script I tried but it is giving Illegal variable name Error
#!/bin/csh -f
if (-r fruits_bkup.txt) then
rm fruits_bkup.txt
endif
yes|cp fruits.txt fruits_bkup.txt
foreach word ("`cat waiver.txt`")
sed -i "/${word}/s/$/ ,waived/" fruits_bkup.txt
end
If I replace the double quotes with a single quotes in the sed command, nothing happens to the report.
Thanks!
Was expecting:
i love apple_tart as a desert
banana is full of potassium and iron,waive
there are so many helath benefits of apple eating
the king of fruit is mango
there are apple_pie of many variety,waive
Got: Illegal variable name Error
Avoiding the quirks of the csh
shell, we may solve this with a single awk
command (which you may put into a csh
script if you so wish). This also allows us to reduce the number of passes we need to make over the input file (we only need a single pass).
awk 'NR==FNR { query[++n] = $0; next } { for (i in query) if ($0 ~ query[i]) { $0 = $0 ",waive"; break } };1' waive.txt report.txt
The command first reads the lines of the first file, waive.txt
, into the associative array query
. When we reach the second file, report.txt
, we iterate over the patterns in query
and test each against the current line. If there is a match, we add ,waive
to the end of the line and terminate the loop.
At the end, the trailing 1
causes the (possibly modified) line to be outputted.
Note that this uses the text from the first file as regular expressions. Would you want to do string comparisons instead, use index(query[i],$0)
in place of $0 ~ query[i]
in the code.
To write the result back to the original file, pipe the output to sponge report.txt
, or redirect it to a new filename and then rename that new file to report.txt
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments