You can use sed or awk command to replace one substring for another string in shell script
Replace all occurrences of a string in a file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
## Create a file with some lines cat << 'EOF' > file.txt hello aws hello azure hello gcp hello oci top three cloud are aws, oci, gcp EOF ## Replace all occurance of a string in a file ## sed -i "s/oldstr/newstr/g" file sed -i "s/oci/alibaba/g" file.txt cat file.txt ## Returns ## hello aws ## hello azure ## hello gcp ## hello alibaba ## top three cloud are aws, alibaba, gcp |
Replace n occurrence of a string in a file:
1 2 3 4 5 6 7 8 9 10 11 |
## Replace n occurance of a string in a file ## sed -i ':a;N;$!ba;s/oldstr/newstr/n' file sed -i ':a;N;$!ba;s/alibaba/azure/2' file.txt cat file.txt ## Returns ## hello aws ## hello azure ## hello gcp ## hello alibaba ## top three cloud are aws, azure, gcp |
Replace a range of occurrences of a string in a file:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## Replace a range (n,m) of occurance of a string in a file ## awk '/oldstr/{c+=1}{if(c>n && c ## file > temp && mv temp file awk '/hello/{c+=1}{if(c>1 && c<4){sub("hello","hi",$0)};print}' \ file.txt > temp && mv temp file.txt cat file.txt ## Returns ## hello aws ## hi azure ## hi gcp ## hello alibaba ## top three cloud are aws, azure, gcp |