简体   繁体   中英

How to append a String to all lines of all files in a directory in Bash?

I want to append a String to all lines of files inside a directory hierarchy. I know how to do this for a single file by the sed command :

sed -e 's/$/ sample string/' -i test.txt

but how to write a script that does this for all files found in a directory hierarchy (and its sub-directories and sub-sub-directories so on...)?

for all files found in a directory hierarchy (and its sub-directories and sub-sub-directories so on...)

This is a job for find , plain and simple.

For example, the command:

find . -type f -exec sed -i 's/$/ sample string/' {} \;

will execute that sed command on all regular files in and under the current directory.

The find command has lots more options (depth limiting, not crossing filesystem boundaries, only working on certain file masks, and so on) that you can use but the ones above are probably all you need for your immediate question.


Keep in mind that sed -i is in-place editing so, if you make a mistake, you better make sure you've backed up the original files before-hand.

In the case where you want to create new files (as requested in a comment), you can bypass the -i and create new files. The safest way to do this is probably by putting the commands you want to execute in an executable script (eg, myprog.sh ):

#!/usr/bin/env bash

origName="$1"
newName="$1.new"
sed s/$/ sample string/' "${origName}" > "${newName}"

Then call that from your find :

find . -type f -exec myprog.sh {} \;

Then you can make the target file name an arbitrarily complex value calculated from the original.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM