-2

i try to concatenate two .txt in loops, here is the file

mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ ls
Alnus1.txt  Alnus2.txt  Alnus3.txt  Alnus4.txt  Bobi1.txt  Bobi2.txt  Bobi3.txt  Bobi4.txt`

I try to combine Alnus1 and Bobi1 into a new file named combination1.txt

I am new in bash and need guidance I here is my failed trial, please take a look.

mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ ls
Alnus1.txt  Alnus2.txt  Alnus3.txt  Alnus4.txt  Bobi1.txt  Bobi2.txt  Bobi3.txt  Bobi4.txt
mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ for name in *1.txt
> do
> other = "${name/1/1}"
> cat "$name" "%other" > "$combination1"
> done
other: command not found
-bash: : No such file or directory
other: command not found
-bash: : No such file or directory

I try to combine Alnus1 and Bobi1 into a new file named combination1.txt

Fravadona
  • 13,917
  • 1
  • 23
  • 35
  • 1
    Try https://shellcheck.net/ before asking for human assistance. `%variable` is a DOS construct and has no special meaning in Bash; you mean `$variable` – tripleee Nov 20 '22 at 10:31
  • Duplicate of https://stackoverflow.com/questions/28725333/looping-over-pairs-of-values-in-bash – tripleee Nov 20 '22 at 10:34

2 Answers2

1

This is probably what you're looking for:

for file in Alnus*.txt; do
    suffix=${file#Alnus}
    cat "$file" "Bobi$suffix" > "combination$suffix"
done

The value of ${file#Alnus} is the value of the variable file with the string Alnus removed from the beginning.

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
-1

edit: updated snippets according to the tips in the comments

If you know exactly how many files there are, you can do this:

for i in {1..4}; do
        cat "Alnus${i}.txt" "Bobi${i}.txt" > "combination${i}.txt"
done

If you don't, you can use find . -name "Alus*.txt" | wc -l to make it work for any number of files (assuming you are always starting the count from 1), like this:

for i in $(seq 1 "$(find . -name "Alnus*.txt" | wc -l)"); do
        cat "Alnus${i}.txt" "Bobi${i}.txt" > "combination${i}.txt"
done
Amit Itzkovitch
  • 175
  • 1
  • 7
  • 2
    Unfortunately, this has numerous beginner bugs and antipatterns. Try https://shellcheck.net/ and see also https://stackoverflow.com/questions/65538947/counting-lines-or-enumerating-line-numbers-so-i-can-loop-over-them-why-is-this – tripleee Nov 20 '22 at 10:32
  • Thanks, I now used shellcheck.net and updated the examples. I didn't quite get the reference to the StackOverflow post about processing files line by line. Can you please elaborate on what I missed there? – Amit Itzkovitch Nov 20 '22 at 11:53
  • Counting the number of matches just so you can loop over them again is conceptually similar. Simply `for f in Alnus*.txt; do cat "$f" "Bob${f#Alnus}"` etc – tripleee Nov 20 '22 at 12:18