Replace Text in Variables & Single/Multiple-Files in UNIX

Shell Script is fun. I love it when I know which commands to use. There are almost thousands of Here is a simple trick to Replace Text and Variables in Files in UNIX. We will use command sed – it is very useful to find and replace text in single or multiple files.

Replace Text in Single File

Replacing hello with hello_world in a single file.
sed -i 's/hello/hello_world/g' somefile.txt
Code language: Arduino (arduino)
Check the arguments
  • -i = edit the file “in-place” – sed will directly modify the file if it finds anything to replace
  • s = substitute the following text
  • hello = what you want to substitute
  • hello_world = what you want to replace
  • g = global, match all occurrences in the line

Replace Text in Multiple Files

Following command will replace hello with hello_world in multiple files in one go.
sed -i 's/hello/hello_world/g' *.txt
Code language: Arduino (arduino)

Replace Value of Variable

I had a requirement in shell script to replace value of a variable and use it somewhere. For example: Say variable $path has value “root/user/home” and I need to replace “/” with “-” so that the value looks like “root-user-home”.
${variable//search/replace}
Code language: Arduino (arduino)
  • variable – Is name of the variable you want to replace value.
  • search – String in variable you want to replace.
  • replace – String you want to replace with.

View Comments

Share
Published by
Gaurav Patel
Tags: shell Unix Shell Script

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago