0

I use this code according to this question.

$ names=(file1.txt file2.txt file3.txt) # Declare array

$ printf 's/%s/a-&/g\n' "${names[@]%.txt}" # Generate sed replacement script
s/file1/a-&/g
s/file2/a-&/g
s/file3/a-&/g

$ sed -f <(printf 's/%s/a-&/g\n' "${names[@]%.txt}") f.txt
TEXT
\connect{a-file1}
\begin{a-file2}
\connect{a-file3}
TEXT
75

How to make conditions that solve the following problem please?

names=(file1.txt file2.txt file3file2.txt) 

I mean that there is a world in the names of files that is repeated as a part of another name of file. Then there is added a- more times.

I tried

sed -f <(printf 's/{%s}/{s-&}/g\n' "${files[@]%.tex}")

but the result is

\input{a-{file1}}

I need to find {%s} and a- place between { and %s

Archie
  • 93
  • 2
  • 9

2 Answers2

1

It's not clear from the question how to resolve conflicting input. In particular, the code will replace any instance of file1 with a-file1, even things like 'foofile1'.

On surface, the goal seems to be to change tokens (e.g., foofile1 should not be impacted by by file1 substitution. This could be achieved by adding word boundary assertion (\b) - before and after the filename. This will prevent the pattern from matching inside other longer file names.

printf 's/\\b%s\\b/a-&/g\n' "${names[@]%.txt}"
dash-o
  • 13,723
  • 1
  • 10
  • 37
1

Since this explanation is too long for comment so adding an answer here. I am not sure if my previous answer was clear or not but my answer takes care of this case and will only replace exact file names only and NOT mix of file names.

Lets say following is array value and Input_file:

names=(file1.txt file2.txt file3file2.txt)
echo "${names[*]}"
file1.txt file2.txt file3file2.txt

cat file1
TEXT
\connect{file1}
\begin{file2}
\connect{file3}
TEXT
75

Now when we run following code:

awk -v arr="${names[*]}" '
BEGIN{
  FS=OFS="{"
  num=split(arr,array," ")
  for(i=1;i<=num;i++){
    sub(/\.txt/,"",array[i])
    array1[array[i]"}"]
  }
}
$2 in array1{
  $2="a-"$2
}
1
' file1

Output will be as follows. You could see file3 is NOT replaced since it was NOT present in array value.

TEXT
\connect{a-file1}
\begin{a-file2}
\connect{file3}
TEXT
75
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93