BASH | Adding elements in all files of a specific directory bash

118 Views Asked by At

Assuming that I have in the folder :

MyFolder

the following files :

File1.txt File2.txt File3.txt File9.txt Bob.txt

I want to apply the following algorithm, but I don't know how to do it in Bash (actually the loop For is what I don't manage to do) :

 For (each file of MyFolder directory)
      add "<end>" at the end of the current text file
 EndFor

What is the proper syntax in bash for that ?

Thank you in advance for your help.

3

There are 3 best solutions below

6
fedorqui On BEST ANSWER

This can make it:

for file in /your/dir/*
do
    echo "<end>" >> "$file"
done

In case you have some dirs inside, you may get the error bash: XX: Is a directory. To avoid seeing them, you can add 2>/dev/null to the end of the echo command:

echo "<end>" >> "$file" 2>/dev/null

Or even better (thanks Barmar), check if they are files:

[ -f "$file" ] && echo "<end>" >> "$file"

Which is a short way of doing an if-condition:

if [ -f "$file" ]; then
   echo "<end>" >> "$file"
fi
3
phschoen On

one way would be something like this

#!/bin/bash
folder="myfolder"
for i in `find $folder/ -type f`
do
    echo $i
    echo "<end>" >> "$i"
done
0
svante On

Here is a find one liner :

find /your/dir/ -maxdepth 1 -type f -exec sh -c 'echo "<end>" >> {}' \;

Where -maxdepth 1 keeps from including files in subfolders, -type f is for finding files only and -exec fires the echo command for each found item.