Kaleb Blue
Kaleb Blue

Reputation: 507

Linux find and replace from command line

I'm looking for a linux command line script to do the following.

Assume I have a file

ABC|1|READ11|Reading|1
ABj|2|READ11|Reading|2
CBD|3|WRIT11|Reading|3
BCD|4|READ11|Reading|4
CDE|5|WRIT11|Reading|5
CBA|6|READ11|Reading|6

for every line that start with the letter 'C', if it has 'WRIT11', replace with 'REPL11'

File after script

ABC|1|READ11|Reading|1
ABj|2|READ11|Reading|2
CBD|3|REPL11|Reading|3
BCD|4|READ11|Reading|4
CDE|5|REPL11|Reading|5
CBA|6|READ11|Reading|6

Upvotes: 1

Views: 1431

Answers (2)

fancyPants
fancyPants

Reputation: 51878

It can be done like this:

sed 's/\(^C.*\)WRIT11/\1REPL11/g' your_file

Explanation:

s/search_this/replace_it_with_this/g s at the beginning is for search, the g at the end means globally, not just for one line.

In the search_this part the part within \( and \) can be written as \1 in the replace_it_with_this part.

The ^C means there's a C at the beginning of the line and the followed . means any character and the * means that the preceeding character can occur not at all or multiple times.

Upvotes: 3

nopasara
nopasara

Reputation: 536

Use something like this:

awk -F'|' '($1 ~ /^C.*$/) && ($3 =="WRIT11")                      \
           {print $1"|"$2"|REPL11|"$4"|"$5; next;}{print;}' file

Upvotes: 0

Related Questions