Home > database >  How to save a list of all files in a directory in a single text file and add prefixes and suffixes?
How to save a list of all files in a directory in a single text file and add prefixes and suffixes?

Time:10-03

I am trying to save a list of files in a directory into a single file using

ls > output.txt

Let's say we have in the directory:

a.txt
b.txt
c.txt

I want to modify the names of these files in the output.txt to be like:

1a.txt$
1b.txt$
1c.txt$

CodePudding user response:

#!/bin/sh -x
for f in *.txt
do
nf=$(echo "${f}" | sed 's@^@1@')
mv -v "${f}" "${nf}"
done

CodePudding user response:

Another easy way use AWK to change content and save to file via .tmp

This script will print content how you want. Just add "1" and "$" to begining and ending accordingly.

cat output.txt  | awk '{print "1"$1"$"}'

And then you can save to original file as you want by extending command && (if success then next )

cat output.txt  | awk '{print "1"$1"$"}' > output.txt.tmp && mv output.txt.tmp output.txt
  • Related