How to Add a String to the Beginning of Each File in a Folder in Bash

How can I add a string to the beginning of each file in a folder in bash?

This will do that. You could make it more efficient if you are doing the same text to each file...

for f in *; do 
echo "whatever" > tmpfile
cat $f >> tmpfile
mv tmpfile $f
done

Add a prefix string to beginning of each line


# If you want to edit the file in-place
sed -i -e 's/^/prefix/' file

# If you want to create a new file
sed -e 's/^/prefix/' file > file.new

If prefix contains /, you can use any other character not in prefix, or
escape the /, so the sed command becomes

's#^#/opt/workdir#'
# or
's/^/\/opt\/workdir/'

How can I prepend a string to the beginning of each line in a file?

a one-line awk command should do the trick also:

awk '{print "prefix" $0}' file

How to use find to append a string to every file in a directory

You need to instruct the shell to do it:

find . -type f ! -path "./.git/*" -exec sh -c "echo hello world >> {}" \;

Add a text to the beginning of multiple files in multiple folders

If I understand correctly:

for i in `find . -name "[pU]" ` ; do echo "some string 3" > $i.new ; cat < $i >> $i.new ; mv -f $i.new $i; done

How do I add a string to the beginning of the name of a collection of files in another directory using shell

You could use the following one-liner (assuming you're on the project folder):

ls reports/*xml | awk -F '/' '{print "mv "$0" "$1"/TEST-"$2}' | sh

Is not as clean as yours, but it should give the same result.

How to insert a text at the beginning of a file?

sed can operate on an address:

$ sed -i '1s/^/<added text> /' file

What is this magical 1s you see on every answer here? Line addressing!.

Want to add <added text> on the first 10 lines?

$ sed -i '1,10s/^/<added text> /' file

Or you can use Command Grouping:

$ { echo -n '<added text> '; cat file; } >file.new
$ mv file{.new,}

In Bash, how do I add a string after each line in a file?

If your sed allows in place editing via the -i parameter:

sed -e 's/$/string after each line/' -i filename

If not, you have to make a temporary file:

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename


Related Topics



Leave a reply



Submit