0

I'm new to unix and I'm having a hard time doing this loop.

I have a directory with a list of files and I'm able to list all of those files in a text file.

I have a text file that contains the following contents:

  • FileName01.xml
  • FileName02.xml
  • FileName03.xml
  • FileNameNN.xml

I want to create a text file separately for each of those contents. The output should be like this:

-File name of the text file: Filename01.txt -Content of the text file: FileName01.xml

And so on and so forth

I'm trying using for loop to create a text file for each of those contents and I can't seem to make it.

This is the current script that I'm working on:

#!/bin/bash
ls /directory/input > filelist.txt
for f in filelist.txt;
do
    printf f > 'file_*.txt'
done
doneal24
  • 5,059
  • for f in $(ls /directory/input);do echo $f > ${f}.txt; done Is this the answer you need? I use a translation software, can understand the wrong question – 山河以无恙 Dec 04 '22 at 16:23
  • @山河以无恙 please don't use $(ls): See https://unix.stackexchange.com/questions/128985/why-not-parse-ls-and-what-to-do-instead ; also, even if it worked reliably, it would be less useful than for f in /directory/input/* ; …, which is nicer.. – Marcus Müller Dec 04 '22 at 21:10

1 Answers1

2

I suggest

#!/bin/bash

shopt -s nullglob

for f in /directory/input/.xml; do bn=${f##/} printf '%s\n' "$bn" > "${f%.xml}.txt" done

See Shell Parameter Expansion for an explanation of the prefix and suffix removal syntax.

steeldriver
  • 81,074