lola
lola

Reputation: 5789

shell script to update a set of txt files

I would like using shell or any script to modify all txt files available in myfolder as follow

 test = data(x, y);

with

test = data(z,x,y);  // by adding z

and :

 test.value(f1, "directory_1/directory_2/directory_3/file");

with

test.value(f1, "/directory_3/file"); // by removing directory_1/directory_2

Upvotes: 1

Views: 468

Answers (2)

perreal
perreal

Reputation: 98098

Using sed with bash:

for i in *.txt; do
  if [ -f $i ]; then
    sed -i 's!test = data(\s*x,\s*y)!test = data(z,x,y)!' "$i"
    sed -i 's!test.value(f1, "[^/]*/[^/]*\(/[^"]*\)");!test.value(f1, "\1");!' "$i"
  fi  
done

Upvotes: 1

rush
rush

Reputation: 2564

cd myfolder
for FILE in *txt ; do
    sed -i 's/test = data(x,\s*y);/test = data(z,x,y);/;/test.value(f1, "/s="[^/]*/[^/]*\(/[^/]*/[^/]*");\)$=\1=;' "$FILE"
done

if your sed isn't GNU, then use

cd myfolder
for FILE in *txt ; do
    sed 's/test = data(x, y);/test = data(z,x,y);/test.value(f1, "/s="[^/]*/[^/]*\(/[^/]*/[^/]*");\)$=\1=;' "$FILE" > "$FILE.tmp"
    mv "${FILE}.tmp" "$FILE"
done

Upvotes: 1

Related Questions