Bash - use filename to append to each line in each file using sed

I have multiple files named as such -> 100.txt, 101.txt, 102.txt, etc.

The files are in the directory. For each of these files, I need to add a number before the extension in the filename for each line in the file.

So if the content of the file 100.txt is:

blahblahblah
blahblahblah
...

      

I need the output:

blahblahblah 100 
blahblahblah 100
...

      

I need to do this using sed

.

My current code looks like this, but it's ugly and not very short:

dir=$1
for file in $dir/*
do
    base=$(basename $file)
    filename="${base%.*}" 
    sed "s/$/ $filename/" $file
done

      

Can you do it this way?

find $dir/* -exec sed ... {} \; 

      

+3


source to share


2 answers


The code you already have is essentially the simplest and shortest way to accomplish a task in bash. The only changes I would make is to pipe -i

in sed

, assuming you are using GNU sed (otherwise you will need to redirect the output to a temporary file, delete the old file, and move the new file in its place) and provide a default value in case $1

empty.



dir="${1:-.}"

      

+3


source


the following command line will find all files with filename only with extension numbers and add the filename (numbers) at the end of each line in that file. (I tested multiple files )

find <directory path> -type f -name '[0-9]*' -exec bash -c 'num=`basename "{}"|sed "s/^\([0-9]\{1,\}\)\..*/\1/"`;sed -i.bak "s/.$/& $num/" "{}"' \;

      



Note: command line using sed, not tested on OS X

replace <directory path>

with your directory path

0


source







All Articles