0

I am beginner to bash scripting and I am not able to find a solution to my problem. I have a list of strings like in input.txt file separated by newline character:

TATAMOTORS
TCS
RELIANCE
MARUTI

I have another file target.txt with more than 1000 lines in csv format which is of the following format:

124,1940000,792,TATAMOTORS,172.1.1.21,mode1,12:00:00,1,21,0,23,23,014,1000,alive,1,17,23

I want to replace the time in field number 7 to 24:00:00 for all the lines where the column 4 (here TATAMOTORS) matches with any of the lines in input.txt file.

Can I do this with a simple bash command/script?

1

Another way using bash and sed:

while read token; do
   sed -i "/$token/{s/,[^,]*/,24:00:00/6}" target.txt
done < input.txt

This script reads input.txt line by line and put line value into token variable.

sed performs replace the 6th match of the regexp only for line that contains $token.

-i option specifies that files are to be edited in-place.

2

You can do it with a simple Awk command/script:

awk -F, '
  BEGIN{OFS=FS} 
  NR==FNR {a[$1]++; next} 
  $4 in a {$7 = "24:00:00"}
  1
' input.txt target.txt
  • a[$1] alone defines an (empty) element; no reason to assign a value to it so ++ could be omitted. or missing something else? – GiannakopoulosJ May 2 at 10:00
  • @GiannakopoulosJ yes I believe that's the case (I almost wrote it that way) but based on others' examples it seems to be more idiomatic to use either a[$1]++ or a[$1]=1 – steeldriver May 2 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.