sed की Basics
In this page:
sed 's/old/new/' file_name
sed 's/old/new/g' file_name
sed -i 's/old/new/g' file_name
Basic Substitution
s/old/new/ command हर line पर old के पहले match को new से substitute करता है। एक trailing g flag के बिना, per line सिर्फ पहला occurrence replace होता है।
उदाहरण: Basic Substitution
#!/bin/bash
echo "cat sat on the cat mat" | sed 's/cat/dog/'
Login to try C/C++/Java/PHP code in the editor
Global Substitution
तीसरे slash के बाद एक g flag add करना substitution को line पर मिले सिर्फ पहले match के बजाय हर match पर apply करता है।
उदाहरण: Global Substitution
#!/bin/bash
echo "cat sat on the cat mat" | sed 's/cat/dog/g'
Login to try C/C++/Java/PHP code in the editor
एक File को In Place Edit करना
sed -i 's/old/new/' file stdout पर change print करने के बजाय file को खुद rewrite करता है। यह destructive है, इसलिए पहले एक sample पर plain (non -i) version test करना worth है।
sed -i बिना confirmation file को overwrite करता है; important files पर इसे चलाने से पहले एक backup रखें या version control उपयोग करें।उदाहरण: Editing a File in Place
#!/bin/bash
echo "version=1.0" > config.txt
sed -i 's/1.0/2.0/' config.txt
cat config.txt
rm -f config.txt
Login to try C/C++/Java/PHP code in the editor
Lines Delete करना
sed Nd line number N delete करता है। sed '/pattern/d' line में कहीं भी pattern से match करने वाली हर line delete करता है, जो comments या blank lines strip करने का एक quick तरीका है।
उदाहरण: Deleting Lines
#!/bin/bash
printf "keep\n# comment\nkeep too\n# another comment\n" > notes.txt
sed '/^#/d' notes.txt
rm -f notes.txt
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि
seddefault रूप से stdout पर print करता है और file को modify नहीं करता जब तक-iउपयोग न हो। - macOS/BSD sed पर
sed -iको बिना argument के उपयोग करना और एक error से टकराना, क्योंकि GNU sed और BSD sed के अलग-isyntax हैं; GNU/Linux पर (इस course के sandbox जैसे)-iबिना एक backup suffix दिए अलग से कोई separate backup suffix नहीं लेता। - Pattern में
.या/जैसे special regex characters को escape न करना, जिससे sed intended से ज़्यादा (या कम) match करता है।
sed 's/old/new/' fileहर line परoldके पहले occurrence कोnewसे replace करता है।- एक
gflag add करना (s/old/new/g) हर line पर हर occurrence replace करता है, सिर्फ पहला नहीं। sed -iresult को stdout पर print करने के बजाय एक file को in place edit करता है।sed 2d fileline 2 delete करता है;sed '/pattern/d' filepattern से match करने वाली हर line delete करता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: