简体   繁体   中英

shell scripting for token replacement in all files in a folder

HI

I am not very good with linux shell scripting.I am trying following shell script to replace

revision number token $rev -<rev number> in all html files under specified directory

cd /home/myapp/test
set repUpRev = "`svnversion`"
echo $repUpRev
grep -lr -e '\$rev -'.$repUpRev.'\$' *.html | xargs sed -i 's/'\$rev -'.$repUpRev.'\$'/'\$rev -.*$'/g'

This seems not working, what is wrong with the above code ?

rev=$(svnversion)
sed -i.bak "s/$rev/some other string/g" *.html

What is $rev in the regexp string? Is it another variable? Or you're looking for a string '$rev'. If latter - I would suggest adding '\\' before $ otherwise it's treated as a special regexp character...

This is how you show the last line:

grep -lr -e '\$rev -'.$repUpRev.'\$' *.html | xargs sed -i 's/'\$rev -'.$repUpRev.'\$'/'\$rev -.*$'/g'

It would help if you showed some input data.

The -r option makes the grep recursive. That means it will operate on files in the directory and its subdirectories. Is that what you intend?

The dots in your grep and sed stand for any character. If you want literal dots, you'll need to escape them.

The final escaped dollar sign in the grep and sed commands will be seen as a literal dollar sign. If you want to anchor to the end of the line you should remove the escape.

The .* works only as a literal string on the right hand side of a sed s command. If you want to include what was matched on the left side, you need to use capture groups. The g modifier on the s command is only needed if the pattern appears more than once in a line.

Using quote, unquote, quote, unquote is hard to read. Use double quotes to permit variable expansion.

Try your grep command by itself without the xargs and sed to see if it's producing a list of files.

This may be closer to what you want:

grep -lr -e "\$rev -.$repUpRev.$" *.html | xargs sed -i "s/\$rev -.$repUpRev.$/\$rev -REPLACEMENT_TEXT/g"

but you'll still need to determine if the g modifier, the dots, the final dollar signs, etc., are what you intend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM