Reputation: 790
I wrote a shell script to identify given word and grep the word next to the given word. Please see my sample input file below. Also I need to write the same file as shown below in my sample output file.
#!/bin/bash
LOGFILE=$1
if [ -f $LOGFILE ]
then
sed -i.bak 's/sqrt(\(\w*\))/sqrt(\1) print(\1)/g' $LOGFILE
else
echo "$LOGFILE not found "
fi
but when I run this shell script nothing happens in my file. Could you please help me?
Example input file:
wewe **sqrt(a+B)** eeenwerer ergv. **sqrt(2x-3)** gtgnwerer ergv. **sqrt(wea*B)** gjjj nwerer ergv. **sqrt(a2/B)** rrnwerer ergv.
Expected file output:
wewe **sqrt(a+B)** eeenwerer ergv. ***write (a+B);*** **sqrt(2x-3)** gtgnwerer ergv. ***write (2x-3);*** ** **sqrt(wea*B)** gjjj nwerer ergv. ***write (wea*B);*** ** **sqrt(a2/B)** rrnwerer ergv.***write (a2/B);*** **
Upvotes: 3
Views: 483
Reputation: 19375
This is somewhat similar to Håkon Hægland's solution, but shorter and works also with old versions of awk
where match()
cannot have 3 arguments:
awk -F'sqrt\\(' '
{ for (i=1; ++i<=NF; )
$i = gensub("(.*)\\)(.*)", "sqrt(\\1)\\2 write(\\1);", 1, $i)
print
} ' $LOGFILE
Upvotes: 0
Reputation: 948
Since you want to find all characters except the ')' after 'sqrt(' - you can use '[^)]*' to match this character set. Then you can explicitly search for the patterns sqrt(...) and sqrt(...(...)....) as two separate cases.
sed '
s/sqrt(\([^)]*)\)/sqrt(\1) print(\1)/g
s/sqrt(\([^)]*([^)]*)[^)]*)\)/sqrt(\1) print(\1)/g
'
This is easier to understand if you change '[^)]*' to Z
sed '
s/sqrt(\(Z)\)/sqrt(\1) print(\1)/g
s/sqrt(\(Z(Z)Z)\)/sqrt(\1) print(\1)/g
'
Upvotes: 0
Reputation: 126
In case the words are in a separate line you cant try this ,It will search for the word and print the line next to it.
awk '/word to search :/{getline;print;}'
Upvotes: 0
Reputation: 40718
You can try:
awk -f mod.awk input.txt
where input.txt
is you input log file, and mod.awk
is:
{
str=str $0 ORS
}
END {
str2=""
prev=""
while(match(str,/sqrt\(([^)]*)\)/,a)) {
cur=substr(str,RSTART,RLENGTH)
end=substr(str,RSTART+RLENGTH)
str2=str2 substr(str,1,RSTART-1) prev cur
str=end
prev="*write(" a[1] ");"
}
print str2 str prev
}
Given input file input.txt
:
wewe sqrt(a+B) eeenwerer ergv. sqrt(2x-3) gtgnwerer ergv. sqrt(wea*B) gjjj nwerer ergv. sqrt(a2/B) rrnwerer ergv.
Running awk -f mod.awk input.txt
gives output:
wewe sqrt(a+B) eeenwerer ergv. *write(a+B);sqrt(2x-3) gtgnwerer ergv. *write(2x-3);sqrt(wea*B) gjjj nwerer ergv. *write(wea*B);sqrt(a2/B) rrnwerer ergv.*write(a2/B);
Upvotes: 1