简体   繁体   中英

How do I loop through a file to create a series of new .docx files?

Background

I have a file of file names like so:

something.txt
another.cpp
whoa.cxx
...

I want to create a corresponding text file for each one as such in the current directory:

./something.txt.docx
./another.cpp.docx
./whoa.cxx.docx

This should be a very simple operation...but the series of commands I am thinking of trying don't seem to make sense logically:

Attempted solutions

  1. Pipe a cat into touch: cat file | touch <not sure what to put here>.docx cat file | touch <not sure what to put here>.docx .

    a. As you can see, I am at a loss of how to append a.docx extension to each file name that I encounter, and I do not know a way to neatly do a regex append in this manner. The touch man page does not seem to be helpful on this front either.

  2. Pipe cat into xargs touch: cat file | xargs -I{} touch {}.docx cat file | xargs -I{} touch {}.docx

    a. My intention was to use the -I option to literally append.docx to get the result seen above. Below is the intended functionality of -I:

    -I replace-str

    Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1.

    This threw the error xargs: .docx: No such file or directory .

Question

How do loop through a file and create corresponding.docx's for each line in the file?

Assuming the file contents are reasonably well formatted and don't have strange corner cases, you can do this:

while IFS= read -r line; do
  touch "$line.docx"
done < input-file-name.txt

I just confirmed that it works on my system.

This can be achieved by below command

ls -1rt | awk '{ print "touch " $0 ".docx" }' | bash

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