Sunday, May 5, 2024
11
rated 0 times [  11] [ 0]  / answers: 1 / hits: 71797  / 3 Years ago, thu, may 13, 2021, 9:13:49

I wish to write a shell script whereby I could read the file from command and edit the file without manual intervention (based on searching some text and replacing it with another).



I need not use any text editor for this....simply text-searching (like using grep) and then replacing it with some other text and saving the changes....


More From » command-line

 Answers
5

That is where sed comes in to play. A sed command has this format:



[pattern1][,pattern2][!] command [args]


It uses regexes so it can/will be a bit difficult. Some basic examples taken from the 2nd link below:




# substitute (find and replace) "foo" with "bar" on each line
sed 's/foo/bar/' # replaces only 1st instance in a line
sed 's/foo/bar/4' # replaces only 4th instance in a line
sed 's/foo/bar/g' # replaces ALL instances in a line
sed 's/(.*)foo(.*foo)/1bar2/' # replace the next-to-last case
sed 's/(.*)foo/1bar/' # replace only the last case

# substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'

# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'

# change "scarlet" or "ruby" or "puce" to "red"
sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g' # most seds
gsed 's/scarlet|ruby|puce/red/g' # GNU sed only


Some references




[#37758] Friday, May 14, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wheance

Total Points: 314
Total Questions: 96
Total Answers: 112

Location: Benin
Member since Thu, Aug 12, 2021
3 Years ago
;