How to update "file2" with data from "file1" using sed in Bash

Home > Search > How-to
  by

Let's say you have a file with multiple lines, and you want to change "World" to "Planet" for the lines in the file that contain "Hello". 

Hello World
Goodbye World

 

A typical sed statement will not suffice, as every occurrence of "World" will be replaced with "Planet"

#]~ sed "s/World/Planet/g" /path/to/file.txt
Hello Planet
Goodbye Planet

 

The following sed statement will change "World" to "Planet" for lines that contain "Hello".

#]~ sed "/Hello/ { s/World/Planet/g; }" /path/to/file.txt
Hello Planet
Goodbye World

 


Let's say you have two files. Both files have an "ID" column with matching data. Both files have a "Notes" column with different data. You want to read the ID and Notes in file1, and then update the Notes in file2.

file1.txt
1234 Hello
5678 World

file2.txt
1234 Greetings
5678 Earth

 

In this example, since 1234 if file1.txt has "Hello", we want to update 1234 to also have "Hello" in file2.txt.

# Create a variable for file1
file1=$(cat /path/to/file1.txt)

# Loop through file2
for myFile1 in $file1
do
  # Get the data from file1 that you want to update in file2
  IDColumn=$(echo $myFile1 | awk '{print $1}'
  NotesColumn=$(echo $myFile1 | awk '{print $2}'

  # Find the col1 data in file2, and then update col2 data
  sed -i "/$IDColumn/ { s/.*./$NotesColumn/g; }" /path/to/file2.txt
done

 

Running this script should update 1234 in file2.txt to have Hello.

file1.txt
1234 Hello
5678 World

file2.txt
1234 Hello
5678 Earth

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments